java之序列化与反序列化
1、这里主要是介绍Protobuf提供的序列化与反序列化的高效性。相对于传统的java提供的序列化来说,Protobuf的效率提高了很多倍。但是也有不足的地方,就是proto在对象序列化的时候抛弃了很多数据。比如:类的相关属性。只保留了数据部分。提高了传输的效率,减少带宽的占用。
2、java的序列化和反序列化
1)对象
import java.io.Serializable; public class User implements Serializable{ private String id;
private String name;
private String age; public User(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} @Override
public String toString() {
return "Usr{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
2)序列化和反序列化
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays; public class UserSerializable { public static void main(String[] args) {
try {
//序列化
User user = new User("1","user","25");
//序列化字节流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//对象读取
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(user);
//转换成字节
byte[] bytes = byteArrayOutputStream.toByteArray();
System.out.println(Arrays.toString(bytes));
//反序列化
//直接读取直接,用对象输入流直接读取出来
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
//读取后转成对应对象
User u = (User) objectInputStream.readObject();
System.out.println(u.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
3)效果(目的对比)
[-84, -19, 0, 5, 115, 114, 0, 30, 99, 111, 109, 46, 116, 114, 111, 121, 46, 97, 112, 112, 108, 105, 99, 97, 116, 105, 111, 110, 46, 106, 97, 118, 97, 46, 85, 115, 101, 114, 122, 36, 125, -10, 11, 54, -23, 51, 2, 0, 3, 76, 0, 3, 97, 103, 101, 116, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 83, 116, 114, 105, 110, 103, 59, 76, 0, 2, 105, 100, 113, 0, 126, 0, 1, 76, 0, 4, 110, 97, 109, 101, 113, 0, 126, 0, 1, 120, 112, 116, 0, 2, 50, 53, 116, 0, 1, 49, 116, 0, 4, 117, 115, 101, 114]
Usr{id='1', name='user', age='25'}
3、Protobuf的使用
1)protoc.exe下载:https://pan.baidu.com/s/1gfaULwv 目的:这个主要是用来创建反序列化的Java文件
2)proto文件
编写一个.proto为后缀的文件,文件内容如下:
option java_package = "com.troy.application.proto";
option java_outer_classname = "UsrProto";
message Usr{
required string id = 1;
required string name = 2;
required string age = 3;
}
说明:java_package class里面的package;java_outer_classname为输出类的名称;message可以当成class看;required要求必填;
下面是具体java对应message的写法。
.proto类型 |
Java 类型 |
C++类型 |
备注 |
double |
double |
double |
|
float |
float |
float |
|
int32 |
int |
int32 |
使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint32。 |
int64 |
long |
int64 |
使用可变长编码方式。编码负数时不够高效——如果你的字段可能含有负数,那么请使用sint64。 |
sint32 |
int |
int32 |
使用可变长编码方式。有符号的整型值。编码时比通常的int32高效。 |
sint64 |
long |
int64 |
使用可变长编码方式。有符号的整型值。编码时比通常的int64高效。 |
fixed32 |
int |
uint32 |
总是4个字节。如果数值总是比总是比228大的话,这个类型会比uint32高效。 |
fixed64 |
long |
uint64 |
总是8个字节。如果数值总是比总是比256大的话,这个类型会比uint64高效。 |
sfixed32 |
int |
int32 |
总是4个字节。 |
fixed64 |
long |
int64 |
总是8个字节。 |
bool |
boolean |
bool |
|
string |
String |
string |
一个字符串必须是UTF-8编码或者7-bit ASCII编码的文本。 |
bytes |
ByteString |
string |
可能包含任意顺序的字节数据。 |
3)生成Java序列化代码
将.proto文件和protoc.exe 放在同一文件夹
然后编写一个bat文件,或者用cmd命令执行
protoc ./user.proto --java_out=./
最后会在当前目录生成一个文件
将包里面的java文件拷到对应包下面就可以使用了
4)proto的序列化和反序列化
a、对象(为了检测序列化多少,采用同一个对象只是改了一下名称)
import java.io.Serializable; public class Usr implements Serializable{ private String id;
private String name;
private String age; public Usr(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
} public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} @Override
public String toString() {
return "Usr{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
b、proto序列化文件
public final class UsrProto {
private UsrProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface UsrOrBuilder extends
// @@protoc_insertion_point(interface_extends:Usr)
com.google.protobuf.MessageOrBuilder { /**
* <code>required string id = 1;</code>
*/
boolean hasId();
/**
* <code>required string id = 1;</code>
*/
String getId();
/**
* <code>required string id = 1;</code>
*/
com.google.protobuf.ByteString
getIdBytes(); /**
* <code>required string name = 2;</code>
*/
boolean hasName();
/**
* <code>required string name = 2;</code>
*/
String getName();
/**
* <code>required string name = 2;</code>
*/
com.google.protobuf.ByteString
getNameBytes(); /**
* <code>required string age = 3;</code>
*/
boolean hasAge();
/**
* <code>required string age = 3;</code>
*/
String getAge();
/**
* <code>required string age = 3;</code>
*/
com.google.protobuf.ByteString
getAgeBytes();
}
/**
* Protobuf type {@code Usr}
*/
public static final class Usr extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Usr)
UsrOrBuilder {
// Use Usr.newBuilder() to construct.
private Usr(com.google.protobuf.GeneratedMessage.Builder builder) {
super(builder);
}
private Usr() {
id_ = "";
name_ = "";
age_ = "";
} @Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Usr(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000001;
id_ = bs;
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
name_ = bs;
break;
}
case 26: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000004;
age_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return UsrProto.internal_static_Usr_descriptor;
} protected FieldAccessorTable
internalGetFieldAccessorTable() {
return UsrProto.internal_static_Usr_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Usr.class, Builder.class);
} public static final com.google.protobuf.Parser<Usr> PARSER =
new com.google.protobuf.AbstractParser<Usr>() {
public Usr parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Usr(input, extensionRegistry);
}
}; @Override
public com.google.protobuf.Parser<Usr> getParserForType() {
return PARSER;
} private int bitField0_;
public static final int ID_FIELD_NUMBER = 1;
private Object id_;
/**
* <code>required string id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string id = 1;</code>
*/
public String getId() {
Object ref = id_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
id_ = s;
}
return s;
}
}
/**
* <code>required string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} public static final int NAME_FIELD_NUMBER = 2;
private Object name_;
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
public String getName() {
Object ref = name_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} public static final int AGE_FIELD_NUMBER = 3;
private Object age_;
/**
* <code>required string age = 3;</code>
*/
public boolean hasAge() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string age = 3;</code>
*/
public String getAge() {
Object ref = age_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
age_ = s;
}
return s;
}
}
/**
* <code>required string age = 3;</code>
*/
public com.google.protobuf.ByteString
getAgeBytes() {
Object ref = age_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
age_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
} private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false; if (!hasId()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasName()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasAge()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
} public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getIdBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getAgeBytes());
}
unknownFields.writeTo(output);
} private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size; size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getIdBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getAgeBytes());
}
size += unknownFields.getSerializedSize();
memoizedSerializedSize = size;
return size;
} private static final long serialVersionUID = 0L;
public static Usr parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Usr parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Usr parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Usr parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Usr parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Usr parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Usr parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Usr parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Usr parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Usr parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
} public static Builder newBuilder() { return new Builder(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Usr prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); } @Override
protected Builder newBuilderForType(
BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Usr}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Usr)
UsrOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return UsrProto.internal_static_Usr_descriptor;
} protected FieldAccessorTable
internalGetFieldAccessorTable() {
return UsrProto.internal_static_Usr_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Usr.class, Builder.class);
} // Construct using com.troy.application.proto.UsrProto.Usr.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
} private Builder(
BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
id_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
name_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
age_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
return this;
} public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return UsrProto.internal_static_Usr_descriptor;
} public Usr getDefaultInstanceForType() {
return Usr.getDefaultInstance();
} public Usr build() {
Usr result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
} public Usr buildPartial() {
Usr result = new Usr(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.id_ = id_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.name_ = name_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.age_ = age_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
} public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Usr) {
return mergeFrom((Usr)other);
} else {
super.mergeFrom(other);
return this;
}
} public Builder mergeFrom(Usr other) {
if (other == Usr.getDefaultInstance()) return this;
if (other.hasId()) {
bitField0_ |= 0x00000001;
id_ = other.id_;
onChanged();
}
if (other.hasName()) {
bitField0_ |= 0x00000002;
name_ = other.name_;
onChanged();
}
if (other.hasAge()) {
bitField0_ |= 0x00000004;
age_ = other.age_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
} public final boolean isInitialized() {
if (!hasId()) { return false;
}
if (!hasName()) { return false;
}
if (!hasAge()) { return false;
}
return true;
} public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Usr parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Usr) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_; private Object id_ = "";
/**
* <code>required string id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required string id = 1;</code>
*/
public String getId() {
Object ref = id_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
id_ = s;
}
return s;
} else {
return (String) ref;
}
}
/**
* <code>required string id = 1;</code>
*/
public com.google.protobuf.ByteString
getIdBytes() {
Object ref = id_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
id_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string id = 1;</code>
*/
public Builder setId(
String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
}
/**
* <code>required string id = 1;</code>
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000001);
id_ = getDefaultInstance().getId();
onChanged();
return this;
}
/**
* <code>required string id = 1;</code>
*/
public Builder setIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
} private Object name_ = "";
/**
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required string name = 2;</code>
*/
public String getName() {
Object ref = name_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
} else {
return (String) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string name = 2;</code>
*/
public Builder setName(
String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000002);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <code>required string name = 2;</code>
*/
public Builder setNameBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
} private Object age_ = "";
/**
* <code>required string age = 3;</code>
*/
public boolean hasAge() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
/**
* <code>required string age = 3;</code>
*/
public String getAge() {
Object ref = age_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
age_ = s;
}
return s;
} else {
return (String) ref;
}
}
/**
* <code>required string age = 3;</code>
*/
public com.google.protobuf.ByteString
getAgeBytes() {
Object ref = age_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(String) ref);
age_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>required string age = 3;</code>
*/
public Builder setAge(
String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
age_ = value;
onChanged();
return this;
}
/**
* <code>required string age = 3;</code>
*/
public Builder clearAge() {
bitField0_ = (bitField0_ & ~0x00000004);
age_ = getDefaultInstance().getAge();
onChanged();
return this;
}
/**
* <code>required string age = 3;</code>
*/
public Builder setAgeBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
age_ = value;
onChanged();
return this;
} // @@protoc_insertion_point(builder_scope:Usr)
} // @@protoc_insertion_point(class_scope:Usr)
private static final Usr defaultInstance;static {
defaultInstance = new Usr();
} public static Usr getDefaultInstance() {
return defaultInstance;
} public Usr getDefaultInstanceForType() {
return defaultInstance;
} } private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Usr_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Usr_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
String[] descriptorData = {
"\n\nuser.proto\",\n\003Usr\022\n\n\002id\030\001 \002(\t\022\014\n\004name\030" +
"\002 \002(\t\022\013\n\003age\030\003 \002(\tB&\n\032com.troy.applicati" +
"on.protoB\010UsrProto"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
internal_static_Usr_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Usr_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Usr_descriptor,
new String[] { "Id", "Name", "Age", });
} // @@protoc_insertion_point(outer_class_scope)
}
c、proto的序列化与反序列化
import java.util.Arrays; public class UsrSerializable { public static void main(String[] args) {
try {
//建立工具
UsrProto.Usr.Builder builder = UsrProto.Usr.newBuilder();
//设置参数
builder.setId("1").setName("user").setAge("25");
//建立对象
UsrProto.Usr usr = builder.build();
//序列化
byte[] bytes = usr.toByteArray();
System.out.println(Arrays.toString(bytes)); //反序列化
UsrProto.Usr u = UsrProto.Usr.parseFrom(bytes);
System.out.println(u);
} catch (Exception e) {
e.printStackTrace();
}
}
}
4)结果对比:
[10, 1, 49, 18, 4, 117, 115, 101, 114, 26, 2, 50, 53]
id: "1"
name: "user"
age: "25"
4、总结
1)相对于java本身的序列化,proto的序列化精简了很多很多。
2)从数据上面来看没有任何变化,但是proto抛弃了很多东西。
3)这个在http的数据传输上面可以提高很多效率。
4)相对来说,编写上面多做了很多事情,但是考虑数据传输等问题可以采用这种方式!
java之序列化与反序列化的更多相关文章
- java 对象序列化与反序列化
Java序列化与反序列化是什么? 为什么需要序列化与反序列化? 如何实现Java序列化与反序列化? 本文围绕这些问题进行了探讨. 1.Java序列化与反序列化 Java序列化是指把Java对象转换为 ...
- Java对象序列化与反序列化一 JSON
Java对象序列化与反序列化一 JSON 1. 依赖库 jackson-all-1.6.1.jar 2. 代码 public class Student { private String nam ...
- Java对象序列化和反序列化的工具方法
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...
- Java之序列化和反序列化
序列化的对象: package test_demo.SerializableOper; import java.io.Serializable; /* * 序列化对象需要实现序列号接口 * */ pu ...
- Java基础—序列化与反序列化(转载)
转载自: Java序列化与反序列化 1.Java序列化与反序列化 Java序列化是指把Java对象转换为字节序列的过程:而Java反序列化是指把字节序列恢复为Java对象的过程. 2.为什么需要序列化 ...
- Java 中序列化与反序列化
一. 序列化和反序列化概念 Serialization(序列化)是一种将对象以一连串的字节描述的过程:反序列化deserialization是一种将这些字节重建成一个对象的过程.将程序中的对象,放入文 ...
- JAVA的序列化与反序列化
一.为什么要进行序列化 再介绍之前,我们有必要先了解下对象的生命周期,我们知道Java对象的生命周期,也即Java中的远程方法调用RMI也会被用到,在网络中要传输对象的话,则必须要对对象进行序列化,关 ...
- 深入分析Java的序列化与反序列化
序列化是一种对象持久化的手段.普遍应用在网络传输.RMI等场景中.本文通过分析ArrayList的序列化来介绍Java序列化的相关内容.主要涉及到以下几个问题: 怎么实现Java的序列化 为什么实现了 ...
- Java 对象序列化和反序列化
之前的文章中我们介绍过有关字节流字符流的使用,当时我们对于将一个对象输出到流中的操作,使用DataOutputStream流将该对象中的每个属性值逐个输出到流中,读出时相反.在我们看来这种行 ...
随机推荐
- IIS Express 添加MIME映射
IIS Express没有提供图形化界面来配置MIME类型,但提供了配置MIME类型的命令行工具. IIS Express中添加MIME映射.操作如下: 在DOS窗口下进入IIS Express安装目 ...
- C#SendMessage用法
C#SendMessage用法 分类: C#操作内存相关 2011-11-26 23:52 1255人阅读 评论(0) 收藏 举报 函数功能:该函数将指定的消息发送到一个或多个窗口.此函数为指定的窗口 ...
- 雷林鹏分享:Ruby CGI 编程
Ruby CGI 编程 Ruby 是一门通用的语言,不仅仅是一门应用于WEB开发的语言,但 Ruby 在WEB应用及WEB工具中的开发是最常见的. 使用Ruby您不仅可以编写自己的SMTP服务器,FT ...
- idea里面Java文件显示一个x
idea里面Java文件显示一个x,编译时过滤了,setting->builder->compiler->excludes
- Python3 列表List(十一)
list是一种有序可重复的集合,可以随时添加和删除其中的元素. 序列是Python中最基本的数据结构.序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推. ...
- Beta阶段第1周/共2周 Scrum立会报告+燃尽图 04
作业要求与 [https://edu.cnblogs.com/campus/nenu/2018fall/homework/2284] 相同 版本控制:https://git.coding.net/li ...
- (转)Web系统大规模并发——电商秒杀与抢购
电商的秒杀和抢购,对我们来说,都不是一个陌生的东西.然而,从技术的角度来说,这对于Web系统是一个巨大的考验.当一个Web系统,在一秒钟内收到数以万计甚至更多请求时,系统的优化和稳定至关重要.这次我们 ...
- [置顶]
Android 打包apk无敌报错
前言: 这个问题从昨天上午一直到现在,请教了很多大佬,都没有给出确定的解决方案,可能他们也没碰到过可能,不过还是挺感谢他们的建议,一直到今天中午午休,我一直都在想这个问题,就是下面的这个,看了国内很多 ...
- PHP write byte array to file
/********************************************************************************* * PHP write byte ...
- emmc boot_config文件不存在
/******************************************************************************* * emmc boot_config文 ...