一.ProtoBuf 对象的序列化与反序列化
1.proto文件的定义
option java_package = "xss.netty.protobuf";
option java_outer_classname = "EmployeeModule";
message Employee{
required int64 emploee_id = 1;
required string first_name = 2;
required string last_name = 3;
required int32 age = 4;
}
2.protoc.exe 生成相应的java类
protoc.exe ./Employee.proto --java_out=./../xss
3.Java 类文件
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Employee.proto
package xss.netty.protobuf;
public final class EmployeeModule {
private EmployeeModule() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface EmployeeOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required int64 emploee_id = 1;
boolean hasEmploeeId();
long getEmploeeId();
// required string first_name = 2;
boolean hasFirstName();
String getFirstName();
// required string last_name = 3;
boolean hasLastName();
String getLastName();
// required int32 age = 4;
boolean hasAge();
int getAge();
}
public static final class Employee extends
com.google.protobuf.GeneratedMessage
implements EmployeeOrBuilder {
// Use Employee.newBuilder() to construct.
private Employee(Builder builder) {
super(builder);
}
private Employee(boolean noInit) {}
private static final Employee defaultInstance;
public static Employee getDefaultInstance() {
return defaultInstance;
}
public Employee getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return xss.netty.protobuf.EmployeeModule.internal_static_Employee_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return xss.netty.protobuf.EmployeeModule.internal_static_Employee_fieldAccessorTable;
}
private int bitField0_;
// required int64 emploee_id = 1;
public static final int EMPLOEE_ID_FIELD_NUMBER = 1;
private long emploeeId_;
public boolean hasEmploeeId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public long getEmploeeId() {
return emploeeId_;
}
// required string first_name = 2;
public static final int FIRST_NAME_FIELD_NUMBER = 2;
private java.lang.Object firstName_;
public boolean hasFirstName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public String getFirstName() {
java.lang.Object ref = firstName_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (com.google.protobuf.Internal.isValidUtf8(bs)) {
firstName_ = s;
}
return s;
}
}
private com.google.protobuf.ByteString getFirstNameBytes() {
java.lang.Object ref = firstName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((String) ref);
firstName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// required string last_name = 3;
public static final int LAST_NAME_FIELD_NUMBER = 3;
private java.lang.Object lastName_;
public boolean hasLastName() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public String getLastName() {
java.lang.Object ref = lastName_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (com.google.protobuf.Internal.isValidUtf8(bs)) {
lastName_ = s;
}
return s;
}
}
private com.google.protobuf.ByteString getLastNameBytes() {
java.lang.Object ref = lastName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((String) ref);
lastName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// required int32 age = 4;
public static final int AGE_FIELD_NUMBER = 4;
private int age_;
public boolean hasAge() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
public int getAge() {
return age_;
}
private void initFields() {
emploeeId_ = 0L;
firstName_ = "";
lastName_ = "";
age_ = 0;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasEmploeeId()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasFirstName()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasLastName()) {
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.writeInt64(1, emploeeId_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getFirstNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBytes(3, getLastNameBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeInt32(4, age_);
}
getUnknownFields().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
.computeInt64Size(1, emploeeId_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getFirstNameBytes());
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(3, getLastNameBytes());
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(4, age_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static xss.netty.protobuf.EmployeeModule.Employee parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static xss.netty.protobuf.EmployeeModule.Employee parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(xss.netty.protobuf.EmployeeModule.Employee prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements xss.netty.protobuf.EmployeeModule.EmployeeOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return xss.netty.protobuf.EmployeeModule.internal_static_Employee_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return xss.netty.protobuf.EmployeeModule.internal_static_Employee_fieldAccessorTable;
}
// Construct using xss.netty.protobuf.EmployeeModule.Employee.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
emploeeId_ = 0L;
bitField0_ = (bitField0_ & ~0x00000001);
firstName_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
lastName_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
age_ = 0;
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return xss.netty.protobuf.EmployeeModule.Employee.getDescriptor();
}
public xss.netty.protobuf.EmployeeModule.Employee getDefaultInstanceForType() {
return xss.netty.protobuf.EmployeeModule.Employee.getDefaultInstance();
}
public xss.netty.protobuf.EmployeeModule.Employee build() {
xss.netty.protobuf.EmployeeModule.Employee result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private xss.netty.protobuf.EmployeeModule.Employee buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
xss.netty.protobuf.EmployeeModule.Employee result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public xss.netty.protobuf.EmployeeModule.Employee buildPartial() {
xss.netty.protobuf.EmployeeModule.Employee result = new xss.netty.protobuf.EmployeeModule.Employee(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.emploeeId_ = emploeeId_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.firstName_ = firstName_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.lastName_ = lastName_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.age_ = age_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof xss.netty.protobuf.EmployeeModule.Employee) {
return mergeFrom((xss.netty.protobuf.EmployeeModule.Employee)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(xss.netty.protobuf.EmployeeModule.Employee other) {
if (other == xss.netty.protobuf.EmployeeModule.Employee.getDefaultInstance()) return this;
if (other.hasEmploeeId()) {
setEmploeeId(other.getEmploeeId());
}
if (other.hasFirstName()) {
setFirstName(other.getFirstName());
}
if (other.hasLastName()) {
setLastName(other.getLastName());
}
if (other.hasAge()) {
setAge(other.getAge());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasEmploeeId()) {
return false;
}
if (!hasFirstName()) {
return false;
}
if (!hasLastName()) {
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 {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
emploeeId_ = input.readInt64();
break;
}
case 18: {
bitField0_ |= 0x00000002;
firstName_ = input.readBytes();
break;
}
case 26: {
bitField0_ |= 0x00000004;
lastName_ = input.readBytes();
break;
}
case 32: {
bitField0_ |= 0x00000008;
age_ = input.readInt32();
break;
}
}
}
}
private int bitField0_;
// required int64 emploee_id = 1;
private long emploeeId_ ;
public boolean hasEmploeeId() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public long getEmploeeId() {
return emploeeId_;
}
public Builder setEmploeeId(long value) {
bitField0_ |= 0x00000001;
emploeeId_ = value;
onChanged();
return this;
}
public Builder clearEmploeeId() {
bitField0_ = (bitField0_ & ~0x00000001);
emploeeId_ = 0L;
onChanged();
return this;
}
// required string first_name = 2;
private java.lang.Object firstName_ = "";
public boolean hasFirstName() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public String getFirstName() {
java.lang.Object ref = firstName_;
if (!(ref instanceof String)) {
String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
firstName_ = s;
return s;
} else {
return (String) ref;
}
}
public Builder setFirstName(String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
firstName_ = value;
onChanged();
return this;
}
public Builder clearFirstName() {
bitField0_ = (bitField0_ & ~0x00000002);
firstName_ = getDefaultInstance().getFirstName();
onChanged();
return this;
}
void setFirstName(com.google.protobuf.ByteString value) {
bitField0_ |= 0x00000002;
firstName_ = value;
onChanged();
}
// required string last_name = 3;
private java.lang.Object lastName_ = "";
public boolean hasLastName() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public String getLastName() {
java.lang.Object ref = lastName_;
if (!(ref instanceof String)) {
String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
lastName_ = s;
return s;
} else {
return (String) ref;
}
}
public Builder setLastName(String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
lastName_ = value;
onChanged();
return this;
}
public Builder clearLastName() {
bitField0_ = (bitField0_ & ~0x00000004);
lastName_ = getDefaultInstance().getLastName();
onChanged();
return this;
}
void setLastName(com.google.protobuf.ByteString value) {
bitField0_ |= 0x00000004;
lastName_ = value;
onChanged();
}
// required int32 age = 4;
private int age_ ;
public boolean hasAge() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
public int getAge() {
return age_;
}
public Builder setAge(int value) {
bitField0_ |= 0x00000008;
age_ = value;
onChanged();
return this;
}
public Builder clearAge() {
bitField0_ = (bitField0_ & ~0x00000008);
age_ = 0;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Employee)
}
static {
defaultInstance = new Employee(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Employee)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_Employee_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Employee_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\016Employee.proto\"R\n\010Employee\022\022\n\nemploee_" +
"id\030\001 \002(\003\022\022\n\nfirst_name\030\002 \002(\t\022\021\n\tlast_nam" +
"e\030\003 \002(\t\022\013\n\003age\030\004 \002(\005B$\n\022xss.netty.protob" +
"ufB\016EmployeeModule"
};
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;
internal_static_Employee_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Employee_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Employee_descriptor,
new java.lang.String[] { "EmploeeId", "FirstName", "LastName", "Age", },
xss.netty.protobuf.EmployeeModule.Employee.class,
xss.netty.protobuf.EmployeeModule.Employee.Builder.class);
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
4.测试对象的序列化与反序列化
package xss.netty.protobuf;
import java.util.Arrays;
/**
* 测试类 ProtoBuf 对象的序列化与反序列化
*/
public class ProtoBufMain {
public static void main(String[] args) throws Exception {
//对象的序列化操作
EmployeeModule.Employee.Builder builder =EmployeeModule.Employee.newBuilder();
builder.setEmploeeId(1000);
builder.setFirstName("Gam");
builder.setLastName("Xie");
builder.setAge(30);
EmployeeModule.Employee employee = builder.build();
byte[] bytes = employee.toByteArray();
System.out.println("byte length="+bytes.length+",conent="+ Arrays.toString(bytes));
//对象的反序列化操作
EmployeeModule.Employee parseEmployee = EmployeeModule.Employee.parseFrom(bytes);
System.out.println("parse employeeId="+parseEmployee.getEmploeeId());
System.out.println("parse first name="+parseEmployee.getFirstName());
System.out.println("parse last name="+parseEmployee.getLastName());
System.out.println("parse age="+parseEmployee.getAge());
//反序列出来的结果与原数据是一致的
}
}