java之序列化与反序列化

2023-06-02,,

  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之序列化与反序列化.doc》

下载本文的Word格式文档,以方便收藏与打印。