Google Protocol Buffer(簡稱 Protobuf)是 Google 公司內部的混合語言數據標準,目前正在使用的有超過 48?162 種報文格式定義和超過 12?183 個.proto 文件。它們用於 RPC 系統和持續數據存儲系統。
Protocol Buffers 是一種輕便高效的結構化數據存儲格式,可以用於結構化數據串行化,或者序列化。它很適合做爲數據存儲或 RPC 數據交換格式。可用於通信協議、數據存儲等領域的語言無關、平臺無關、可擴展的序列化結構數據格式,目前提供了 C++、Java、Python 三種語言的 API。
雖然 Protobuf 強大、靈活,但是對內存的消耗會比較大,所以並不是移動終端上的最佳選擇。因此基於 Protobuf 修改出了一個新的協議 Nano Protobuf,相比於 Protobuf,NanoProtobuf 去掉了一些複雜的特性,生成的代碼更加小巧、簡單,並且根據移動終端做了特殊的優化,代碼執行效率更高,內存使用效率更佳,更加適用於移動設備。
Protocal Buffers 使用
-
準備
下載對應的文件,我下載的是 protoc-3.9.1-win64.zip 和 protobuf-java-3.9.1.zip 解壓後有一個 protoc.exe 我給它配置了環境變量 -
定義數據結構,新建一個 PersonMsg.proto 文件
message Person {
// ID(必需)
required int32 id = 1;
// 姓名(必需)
required string name = 2;
// email(可選)
optional string email = 3;
// 朋友(集合)
repeated string friends = 4;
}
- 指定命令,–java_out 是輸出 java 格式,C:\Users\Y\Desktop\pro 是輸出位置,PersonMsg.proto 是需要轉換的文件
protoc.exe --java_out=C:\Users\Y\Desktop\pro PersonMsg.proto
- 執行成功後會在指定目錄生成一個 java 文件如下:
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: PersonMsg.proto
public final class PersonMsg {
private PersonMsg() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
public interface PersonOrBuilder extends
// @@protoc_insertion_point(interface_extends:Person)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
boolean hasId();
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
int getId();
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
boolean hasName();
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
java.lang.String getName();
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
boolean hasEmail();
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
java.lang.String getEmail();
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
com.google.protobuf.ByteString
getEmailBytes();
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
java.util.List<java.lang.String>
getFriendsList();
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
int getFriendsCount();
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
java.lang.String getFriends(int index);
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
com.google.protobuf.ByteString
getFriendsBytes(int index);
}
/**
* Protobuf type {@code Person}
*/
public static final class Person extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:Person)
PersonOrBuilder {
private static final long serialVersionUID = 0L;
// Use Person.newBuilder() to construct.
private Person(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Person() {
name_ = "";
email_ = "";
friends_ = com.google.protobuf.LazyStringArrayList.EMPTY;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new Person();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private Person(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
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;
case 8: {
bitField0_ |= 0x00000001;
id_ = input.readInt32();
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;
email_ = bs;
break;
}
case 34: {
com.google.protobuf.ByteString bs = input.readBytes();
if (!((mutable_bitField0_ & 0x00000008) != 0)) {
friends_ = new com.google.protobuf.LazyStringArrayList();
mutable_bitField0_ |= 0x00000008;
}
friends_.add(bs);
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000008) != 0)) {
friends_ = friends_.getUnmodifiableView();
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return PersonMsg.internal_static_Person_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return PersonMsg.internal_static_Person_fieldAccessorTable
.ensureFieldAccessorsInitialized(
PersonMsg.Person.class, PersonMsg.Person.Builder.class);
}
private int bitField0_;
public static final int ID_FIELD_NUMBER = 1;
private int id_;
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
public int getId() {
return id_;
}
public static final int NAME_FIELD_NUMBER = 2;
private volatile java.lang.Object name_;
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
}
}
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int EMAIL_FIELD_NUMBER = 3;
private volatile java.lang.Object email_;
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public boolean hasEmail() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public java.lang.String getEmail() {
java.lang.Object ref = email_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
email_ = s;
}
return s;
}
}
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public com.google.protobuf.ByteString
getEmailBytes() {
java.lang.Object ref = email_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
email_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FRIENDS_FIELD_NUMBER = 4;
private com.google.protobuf.LazyStringList friends_;
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public com.google.protobuf.ProtocolStringList
getFriendsList() {
return friends_;
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public int getFriendsCount() {
return friends_.size();
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public java.lang.String getFriends(int index) {
return friends_.get(index);
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public com.google.protobuf.ByteString
getFriendsBytes(int index) {
return friends_.getByteString(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
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;
}
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt32(1, id_);
}
if (((bitField0_ & 0x00000002) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, name_);
}
if (((bitField0_ & 0x00000004) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, email_);
}
for (int i = 0; i < friends_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, friends_.getRaw(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(1, id_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, name_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, email_);
}
{
int dataSize = 0;
for (int i = 0; i < friends_.size(); i++) {
dataSize += computeStringSizeNoTag(friends_.getRaw(i));
}
size += dataSize;
size += 1 * getFriendsList().size();
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof PersonMsg.Person)) {
return super.equals(obj);
}
PersonMsg.Person other = (PersonMsg.Person) obj;
if (hasId() != other.hasId()) return false;
if (hasId()) {
if (getId()
!= other.getId()) return false;
}
if (hasName() != other.hasName()) return false;
if (hasName()) {
if (!getName()
.equals(other.getName())) return false;
}
if (hasEmail() != other.hasEmail()) return false;
if (hasEmail()) {
if (!getEmail()
.equals(other.getEmail())) return false;
}
if (!getFriendsList()
.equals(other.getFriendsList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasId()) {
hash = (37 * hash) + ID_FIELD_NUMBER;
hash = (53 * hash) + getId();
}
if (hasName()) {
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
}
if (hasEmail()) {
hash = (37 * hash) + EMAIL_FIELD_NUMBER;
hash = (53 * hash) + getEmail().hashCode();
}
if (getFriendsCount() > 0) {
hash = (37 * hash) + FRIENDS_FIELD_NUMBER;
hash = (53 * hash) + getFriendsList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static PersonMsg.Person parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static PersonMsg.Person parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static PersonMsg.Person parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static PersonMsg.Person parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static PersonMsg.Person parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static PersonMsg.Person parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static PersonMsg.Person parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static PersonMsg.Person parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static PersonMsg.Person parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static PersonMsg.Person parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static PersonMsg.Person parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static PersonMsg.Person parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(PersonMsg.Person prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Person}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Person)
PersonMsg.PersonOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return PersonMsg.internal_static_Person_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return PersonMsg.internal_static_Person_fieldAccessorTable
.ensureFieldAccessorsInitialized(
PersonMsg.Person.class, PersonMsg.Person.Builder.class);
}
// Construct using PersonMsg.Person.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
id_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
name_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
email_ = "";
bitField0_ = (bitField0_ & ~0x00000004);
friends_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000008);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return PersonMsg.internal_static_Person_descriptor;
}
@java.lang.Override
public PersonMsg.Person getDefaultInstanceForType() {
return PersonMsg.Person.getDefaultInstance();
}
@java.lang.Override
public PersonMsg.Person build() {
PersonMsg.Person result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public PersonMsg.Person buildPartial() {
PersonMsg.Person result = new PersonMsg.Person(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.id_ = id_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
to_bitField0_ |= 0x00000002;
}
result.name_ = name_;
if (((from_bitField0_ & 0x00000004) != 0)) {
to_bitField0_ |= 0x00000004;
}
result.email_ = email_;
if (((bitField0_ & 0x00000008) != 0)) {
friends_ = friends_.getUnmodifiableView();
bitField0_ = (bitField0_ & ~0x00000008);
}
result.friends_ = friends_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof PersonMsg.Person) {
return mergeFrom((PersonMsg.Person)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(PersonMsg.Person other) {
if (other == PersonMsg.Person.getDefaultInstance()) return this;
if (other.hasId()) {
setId(other.getId());
}
if (other.hasName()) {
bitField0_ |= 0x00000002;
name_ = other.name_;
onChanged();
}
if (other.hasEmail()) {
bitField0_ |= 0x00000004;
email_ = other.email_;
onChanged();
}
if (!other.friends_.isEmpty()) {
if (friends_.isEmpty()) {
friends_ = other.friends_;
bitField0_ = (bitField0_ & ~0x00000008);
} else {
ensureFriendsIsMutable();
friends_.addAll(other.friends_);
}
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
if (!hasId()) {
return false;
}
if (!hasName()) {
return false;
}
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
PersonMsg.Person parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (PersonMsg.Person) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private int id_ ;
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
public boolean hasId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
public int getId() {
return id_;
}
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
public Builder setId(int value) {
bitField0_ |= 0x00000001;
id_ = value;
onChanged();
return this;
}
/**
* <pre>
* ID(必需)
* </pre>
*
* <code>required int32 id = 1;</code>
*/
public Builder clearId() {
bitField0_ = (bitField0_ & ~0x00000001);
id_ = 0;
onChanged();
return this;
}
private java.lang.Object name_ = "";
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public boolean hasName() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
name_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public com.google.protobuf.ByteString
getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public Builder setName(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
name_ = value;
onChanged();
return this;
}
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <code>required string name = 2;</code>
*/
public Builder clearName() {
bitField0_ = (bitField0_ & ~0x00000002);
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
* <pre>
* 姓名(必需)
* </pre>
*
* <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 java.lang.Object email_ = "";
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public boolean hasEmail() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public java.lang.String getEmail() {
java.lang.Object ref = email_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
email_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public com.google.protobuf.ByteString
getEmailBytes() {
java.lang.Object ref = email_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
email_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public Builder setEmail(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
email_ = value;
onChanged();
return this;
}
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public Builder clearEmail() {
bitField0_ = (bitField0_ & ~0x00000004);
email_ = getDefaultInstance().getEmail();
onChanged();
return this;
}
/**
* <pre>
* email(可選)
* </pre>
*
* <code>optional string email = 3;</code>
*/
public Builder setEmailBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000004;
email_ = value;
onChanged();
return this;
}
private com.google.protobuf.LazyStringList friends_ = com.google.protobuf.LazyStringArrayList.EMPTY;
private void ensureFriendsIsMutable() {
if (!((bitField0_ & 0x00000008) != 0)) {
friends_ = new com.google.protobuf.LazyStringArrayList(friends_);
bitField0_ |= 0x00000008;
}
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public com.google.protobuf.ProtocolStringList
getFriendsList() {
return friends_.getUnmodifiableView();
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public int getFriendsCount() {
return friends_.size();
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public java.lang.String getFriends(int index) {
return friends_.get(index);
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public com.google.protobuf.ByteString
getFriendsBytes(int index) {
return friends_.getByteString(index);
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public Builder setFriends(
int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureFriendsIsMutable();
friends_.set(index, value);
onChanged();
return this;
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public Builder addFriends(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureFriendsIsMutable();
friends_.add(value);
onChanged();
return this;
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public Builder addAllFriends(
java.lang.Iterable<java.lang.String> values) {
ensureFriendsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, friends_);
onChanged();
return this;
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public Builder clearFriends() {
friends_ = com.google.protobuf.LazyStringArrayList.EMPTY;
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
* <pre>
* 朋友(集合)
* </pre>
*
* <code>repeated string friends = 4;</code>
*/
public Builder addFriendsBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
ensureFriendsIsMutable();
friends_.add(value);
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:Person)
}
// @@protoc_insertion_point(class_scope:Person)
private static final PersonMsg.Person DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new PersonMsg.Person();
}
public static PersonMsg.Person getDefaultInstance() {
return DEFAULT_INSTANCE;
}
@java.lang.Deprecated public static final com.google.protobuf.Parser<Person>
PARSER = new com.google.protobuf.AbstractParser<Person>() {
@java.lang.Override
public Person parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Person(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<Person> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<Person> getParserForType() {
return PARSER;
}
@java.lang.Override
public PersonMsg.Person getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Person_descriptor;
private static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_Person_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\017PersonMsg.proto\"B\n\006Person\022\n\n\002id\030\001 \002(\005\022" +
"\014\n\004name\030\002 \002(\t\022\r\n\005email\030\003 \001(\t\022\017\n\007friends\030" +
"\004 \003(\t"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
});
internal_static_Person_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Person_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Person_descriptor,
new java.lang.String[] { "Id", "Name", "Email", "Friends", });
}
// @@protoc_insertion_point(outer_class_scope)
}
- 拷貝到項目中,然後測試一下序列化和反序列化操作
項目中要引入庫
Gradle :
implementation 'com.google.protobuf:protobuf-java:3.4.0'
maven :
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.6.1</version>
</dependency>
try {
PersonMsg.Person.Builder personBuilder = PersonMsg.Person.newBuilder();
personBuilder.setId(1);
personBuilder.setName("張三");
personBuilder.setEmail("[email protected]");
personBuilder.addFriends("Friend A");
personBuilder.addFriends("Friend B");
PersonMsg.Person xxg = personBuilder.build();
// 將數據寫到輸出流,如網絡輸出流,這裏就用ByteArrayOutputStream來代替
ByteArrayOutputStream output = new ByteArrayOutputStream();
xxg.writeTo(output);
// -------------- 分割線:上面是發送方,將數據序列化後發送 ---------------
byte[] byteArray = output.toByteArray();
// -------------- 分割線:下面是接收方,將數據接收後反序列化 ---------------
// 接收到流並讀取,如網絡輸入流,這裏用ByteArrayInputStream來代替
ByteArrayInputStream input = new ByteArrayInputStream(byteArray);
// 反序列化
PersonMsg.Person xxg2 = PersonMsg.Person.parseFrom(input);
System.out.println("ID:" + xxg2.getId());
System.out.println("name:" + xxg2.getName());
System.out.println("email:" + xxg2.getEmail());
System.out.println("friend:");
List<String> friends = xxg2.getFriendsList();
for (String friend : friends) {
System.out.println(friend);
}
} catch (IOException e) {
e.printStackTrace();
}
- 以上就是 Protocal Buffers 的使用方法