首页 > 代码库 > google protobuf 简单实例

google protobuf 简单实例

1.定义proto文件:

User.proto

package netty;option java_package="myprotobuf";option java_outer_classname="UserProto";message User{    required int32 ID=1;    required string userName=2;    required string Password=3;    repeated string address=4;}

 

2.用 protoc.exe 生成User.proto的协议文件:

D:\JAVA\protoc-2.5.0-win32>protoc.exe --java_out=. User.proto

// Generated by the protocol buffer compiler.  DO NOT EDIT!// source: User.protopackage myprotobuf;public final class UserProto {  private UserProto() {}  public static void registerAllExtensions(      com.google.protobuf.ExtensionRegistry registry) {  }  public interface UserOrBuilder      extends com.google.protobuf.MessageOrBuilder {    // required int32 ID = 1;    /**     * <code>required int32 ID = 1;</code>     */    boolean hasID();    /**     * <code>required int32 ID = 1;</code>     */    int getID();    // required string userName = 2;    /**     * <code>required string userName = 2;</code>     */    boolean hasUserName();    /**     * <code>required string userName = 2;</code>     */    java.lang.String getUserName();    /**     * <code>required string userName = 2;</code>     */    com.google.protobuf.ByteString        getUserNameBytes();    // required string Password = 3;    /**     * <code>required string Password = 3;</code>     */    boolean hasPassword();    /**     * <code>required string Password = 3;</code>     */    java.lang.String getPassword();    /**     * <code>required string Password = 3;</code>     */    com.google.protobuf.ByteString        getPasswordBytes();    // repeated string address = 4;    /**     * <code>repeated string address = 4;</code>     */    java.util.List<java.lang.String>    getAddressList();    /**     * <code>repeated string address = 4;</code>     */    int getAddressCount();    /**     * <code>repeated string address = 4;</code>     */    java.lang.String getAddress(int index);    /**     * <code>repeated string address = 4;</code>     */    com.google.protobuf.ByteString        getAddressBytes(int index);  }  /**   * Protobuf type {@code netty.User}   */  public static final class User extends      com.google.protobuf.GeneratedMessage      implements UserOrBuilder {    // Use User.newBuilder() to construct.    private User(com.google.protobuf.GeneratedMessage.Builder<?> builder) {      super(builder);      this.unknownFields = builder.getUnknownFields();    }    private User(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }    private static final User defaultInstance;    public static User getDefaultInstance() {      return defaultInstance;    }    public User getDefaultInstanceForType() {      return defaultInstance;    }    private final com.google.protobuf.UnknownFieldSet unknownFields;    @java.lang.Override    public final com.google.protobuf.UnknownFieldSet        getUnknownFields() {      return this.unknownFields;    }    private User(        com.google.protobuf.CodedInputStream input,        com.google.protobuf.ExtensionRegistryLite extensionRegistry)        throws com.google.protobuf.InvalidProtocolBufferException {      initFields();      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 8: {              bitField0_ |= 0x00000001;              iD_ = input.readInt32();              break;            }            case 18: {              bitField0_ |= 0x00000002;              userName_ = input.readBytes();              break;            }            case 26: {              bitField0_ |= 0x00000004;              password_ = input.readBytes();              break;            }            case 34: {              if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) {                address_ = new com.google.protobuf.LazyStringArrayList();                mutable_bitField0_ |= 0x00000008;              }              address_.add(input.readBytes());              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 {        if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) {          address_ = new com.google.protobuf.UnmodifiableLazyStringList(address_);        }        this.unknownFields = unknownFields.build();        makeExtensionsImmutable();      }    }    public static final com.google.protobuf.Descriptors.Descriptor        getDescriptor() {      return myprotobuf.UserProto.internal_static_netty_User_descriptor;    }    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable        internalGetFieldAccessorTable() {      return myprotobuf.UserProto.internal_static_netty_User_fieldAccessorTable          .ensureFieldAccessorsInitialized(              myprotobuf.UserProto.User.class, myprotobuf.UserProto.User.Builder.class);    }    public static com.google.protobuf.Parser<User> PARSER =        new com.google.protobuf.AbstractParser<User>() {      public User parsePartialFrom(          com.google.protobuf.CodedInputStream input,          com.google.protobuf.ExtensionRegistryLite extensionRegistry)          throws com.google.protobuf.InvalidProtocolBufferException {        return new User(input, extensionRegistry);      }    };    @java.lang.Override    public com.google.protobuf.Parser<User> getParserForType() {      return PARSER;    }    private int bitField0_;    // required int32 ID = 1;    public static final int ID_FIELD_NUMBER = 1;    private int iD_;    /**     * <code>required int32 ID = 1;</code>     */    public boolean hasID() {      return ((bitField0_ & 0x00000001) == 0x00000001);    }    /**     * <code>required int32 ID = 1;</code>     */    public int getID() {      return iD_;    }    // required string userName = 2;    public static final int USERNAME_FIELD_NUMBER = 2;    private java.lang.Object userName_;    /**     * <code>required string userName = 2;</code>     */    public boolean hasUserName() {      return ((bitField0_ & 0x00000002) == 0x00000002);    }    /**     * <code>required string userName = 2;</code>     */    public java.lang.String getUserName() {      java.lang.Object ref = userName_;      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()) {          userName_ = s;        }        return s;      }    }    /**     * <code>required string userName = 2;</code>     */    public com.google.protobuf.ByteString        getUserNameBytes() {      java.lang.Object ref = userName_;      if (ref instanceof java.lang.String) {        com.google.protobuf.ByteString b =             com.google.protobuf.ByteString.copyFromUtf8(                (java.lang.String) ref);        userName_ = b;        return b;      } else {        return (com.google.protobuf.ByteString) ref;      }    }    // required string Password = 3;    public static final int PASSWORD_FIELD_NUMBER = 3;    private java.lang.Object password_;    /**     * <code>required string Password = 3;</code>     */    public boolean hasPassword() {      return ((bitField0_ & 0x00000004) == 0x00000004);    }    /**     * <code>required string Password = 3;</code>     */    public java.lang.String getPassword() {      java.lang.Object ref = password_;      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()) {          password_ = s;        }        return s;      }    }    /**     * <code>required string Password = 3;</code>     */    public com.google.protobuf.ByteString        getPasswordBytes() {      java.lang.Object ref = password_;      if (ref instanceof java.lang.String) {        com.google.protobuf.ByteString b =             com.google.protobuf.ByteString.copyFromUtf8(                (java.lang.String) ref);        password_ = b;        return b;      } else {        return (com.google.protobuf.ByteString) ref;      }    }    // repeated string address = 4;    public static final int ADDRESS_FIELD_NUMBER = 4;    private com.google.protobuf.LazyStringList address_;    /**     * <code>repeated string address = 4;</code>     */    public java.util.List<java.lang.String>        getAddressList() {      return address_;    }    /**     * <code>repeated string address = 4;</code>     */    public int getAddressCount() {      return address_.size();    }    /**     * <code>repeated string address = 4;</code>     */    public java.lang.String getAddress(int index) {      return address_.get(index);    }    /**     * <code>repeated string address = 4;</code>     */    public com.google.protobuf.ByteString        getAddressBytes(int index) {      return address_.getByteString(index);    }    private void initFields() {      iD_ = 0;      userName_ = "";      password_ = "";      address_ = com.google.protobuf.LazyStringArrayList.EMPTY;    }    private byte memoizedIsInitialized = -1;    public final boolean isInitialized() {      byte isInitialized = memoizedIsInitialized;      if (isInitialized != -1) return isInitialized == 1;      if (!hasID()) {        memoizedIsInitialized = 0;        return false;      }      if (!hasUserName()) {        memoizedIsInitialized = 0;        return false;      }      if (!hasPassword()) {        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.writeInt32(1, iD_);      }      if (((bitField0_ & 0x00000002) == 0x00000002)) {        output.writeBytes(2, getUserNameBytes());      }      if (((bitField0_ & 0x00000004) == 0x00000004)) {        output.writeBytes(3, getPasswordBytes());      }      for (int i = 0; i < address_.size(); i++) {        output.writeBytes(4, address_.getByteString(i));      }      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          .computeInt32Size(1, iD_);      }      if (((bitField0_ & 0x00000002) == 0x00000002)) {        size += com.google.protobuf.CodedOutputStream          .computeBytesSize(2, getUserNameBytes());      }      if (((bitField0_ & 0x00000004) == 0x00000004)) {        size += com.google.protobuf.CodedOutputStream          .computeBytesSize(3, getPasswordBytes());      }      {        int dataSize = 0;        for (int i = 0; i < address_.size(); i++) {          dataSize += com.google.protobuf.CodedOutputStream            .computeBytesSizeNoTag(address_.getByteString(i));        }        size += dataSize;        size += 1 * getAddressList().size();      }      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 myprotobuf.UserProto.User parseFrom(        com.google.protobuf.ByteString data)        throws com.google.protobuf.InvalidProtocolBufferException {      return PARSER.parseFrom(data);    }    public static myprotobuf.UserProto.User parseFrom(        com.google.protobuf.ByteString data,        com.google.protobuf.ExtensionRegistryLite extensionRegistry)        throws com.google.protobuf.InvalidProtocolBufferException {      return PARSER.parseFrom(data, extensionRegistry);    }    public static myprotobuf.UserProto.User parseFrom(byte[] data)        throws com.google.protobuf.InvalidProtocolBufferException {      return PARSER.parseFrom(data);    }    public static myprotobuf.UserProto.User parseFrom(        byte[] data,        com.google.protobuf.ExtensionRegistryLite extensionRegistry)        throws com.google.protobuf.InvalidProtocolBufferException {      return PARSER.parseFrom(data, extensionRegistry);    }    public static myprotobuf.UserProto.User parseFrom(java.io.InputStream input)        throws java.io.IOException {      return PARSER.parseFrom(input);    }    public static myprotobuf.UserProto.User parseFrom(        java.io.InputStream input,        com.google.protobuf.ExtensionRegistryLite extensionRegistry)        throws java.io.IOException {      return PARSER.parseFrom(input, extensionRegistry);    }    public static myprotobuf.UserProto.User parseDelimitedFrom(java.io.InputStream input)        throws java.io.IOException {      return PARSER.parseDelimitedFrom(input);    }    public static myprotobuf.UserProto.User parseDelimitedFrom(        java.io.InputStream input,        com.google.protobuf.ExtensionRegistryLite extensionRegistry)        throws java.io.IOException {      return PARSER.parseDelimitedFrom(input, extensionRegistry);    }    public static myprotobuf.UserProto.User parseFrom(        com.google.protobuf.CodedInputStream input)        throws java.io.IOException {      return PARSER.parseFrom(input);    }    public static myprotobuf.UserProto.User 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 Builder.create(); }    public Builder newBuilderForType() { return newBuilder(); }    public static Builder newBuilder(myprotobuf.UserProto.User 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;    }    /**     * Protobuf type {@code netty.User}     */    public static final class Builder extends        com.google.protobuf.GeneratedMessage.Builder<Builder>       implements myprotobuf.UserProto.UserOrBuilder {      public static final com.google.protobuf.Descriptors.Descriptor          getDescriptor() {        return myprotobuf.UserProto.internal_static_netty_User_descriptor;      }      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable          internalGetFieldAccessorTable() {        return myprotobuf.UserProto.internal_static_netty_User_fieldAccessorTable            .ensureFieldAccessorsInitialized(                myprotobuf.UserProto.User.class, myprotobuf.UserProto.User.Builder.class);      }      // Construct using myprotobuf.UserProto.User.newBuilder()      private Builder() {        maybeForceBuilderInitialization();      }      private Builder(          com.google.protobuf.GeneratedMessage.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();        iD_ = 0;        bitField0_ = (bitField0_ & ~0x00000001);        userName_ = "";        bitField0_ = (bitField0_ & ~0x00000002);        password_ = "";        bitField0_ = (bitField0_ & ~0x00000004);        address_ = com.google.protobuf.LazyStringArrayList.EMPTY;        bitField0_ = (bitField0_ & ~0x00000008);        return this;      }      public Builder clone() {        return create().mergeFrom(buildPartial());      }      public com.google.protobuf.Descriptors.Descriptor          getDescriptorForType() {        return myprotobuf.UserProto.internal_static_netty_User_descriptor;      }      public myprotobuf.UserProto.User getDefaultInstanceForType() {        return myprotobuf.UserProto.User.getDefaultInstance();      }      public myprotobuf.UserProto.User build() {        myprotobuf.UserProto.User result = buildPartial();        if (!result.isInitialized()) {          throw newUninitializedMessageException(result);        }        return result;      }      public myprotobuf.UserProto.User buildPartial() {        myprotobuf.UserProto.User result = new myprotobuf.UserProto.User(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.userName_ = userName_;        if (((from_bitField0_ & 0x00000004) == 0x00000004)) {          to_bitField0_ |= 0x00000004;        }        result.password_ = password_;        if (((bitField0_ & 0x00000008) == 0x00000008)) {          address_ = new com.google.protobuf.UnmodifiableLazyStringList(              address_);          bitField0_ = (bitField0_ & ~0x00000008);        }        result.address_ = address_;        result.bitField0_ = to_bitField0_;        onBuilt();        return result;      }      public Builder mergeFrom(com.google.protobuf.Message other) {        if (other instanceof myprotobuf.UserProto.User) {          return mergeFrom((myprotobuf.UserProto.User)other);        } else {          super.mergeFrom(other);          return this;        }      }      public Builder mergeFrom(myprotobuf.UserProto.User other) {        if (other == myprotobuf.UserProto.User.getDefaultInstance()) return this;        if (other.hasID()) {          setID(other.getID());        }        if (other.hasUserName()) {          bitField0_ |= 0x00000002;          userName_ = other.userName_;          onChanged();        }        if (other.hasPassword()) {          bitField0_ |= 0x00000004;          password_ = other.password_;          onChanged();        }        if (!other.address_.isEmpty()) {          if (address_.isEmpty()) {            address_ = other.address_;            bitField0_ = (bitField0_ & ~0x00000008);          } else {            ensureAddressIsMutable();            address_.addAll(other.address_);          }          onChanged();        }        this.mergeUnknownFields(other.getUnknownFields());        return this;      }      public final boolean isInitialized() {        if (!hasID()) {                    return false;        }        if (!hasUserName()) {                    return false;        }        if (!hasPassword()) {                    return false;        }        return true;      }      public Builder mergeFrom(          com.google.protobuf.CodedInputStream input,          com.google.protobuf.ExtensionRegistryLite extensionRegistry)          throws java.io.IOException {        myprotobuf.UserProto.User parsedMessage = null;        try {          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);        } catch (com.google.protobuf.InvalidProtocolBufferException e) {          parsedMessage = (myprotobuf.UserProto.User) e.getUnfinishedMessage();          throw e;        } finally {          if (parsedMessage != null) {            mergeFrom(parsedMessage);          }        }        return this;      }      private int bitField0_;      // required int32 ID = 1;      private int iD_ ;      /**       * <code>required int32 ID = 1;</code>       */      public boolean hasID() {        return ((bitField0_ & 0x00000001) == 0x00000001);      }      /**       * <code>required int32 ID = 1;</code>       */      public int getID() {        return iD_;      }      /**       * <code>required int32 ID = 1;</code>       */      public Builder setID(int value) {        bitField0_ |= 0x00000001;        iD_ = value;        onChanged();        return this;      }      /**       * <code>required int32 ID = 1;</code>       */      public Builder clearID() {        bitField0_ = (bitField0_ & ~0x00000001);        iD_ = 0;        onChanged();        return this;      }      // required string userName = 2;      private java.lang.Object userName_ = "";      /**       * <code>required string userName = 2;</code>       */      public boolean hasUserName() {        return ((bitField0_ & 0x00000002) == 0x00000002);      }      /**       * <code>required string userName = 2;</code>       */      public java.lang.String getUserName() {        java.lang.Object ref = userName_;        if (!(ref instanceof java.lang.String)) {          java.lang.String s = ((com.google.protobuf.ByteString) ref)              .toStringUtf8();          userName_ = s;          return s;        } else {          return (java.lang.String) ref;        }      }      /**       * <code>required string userName = 2;</code>       */      public com.google.protobuf.ByteString          getUserNameBytes() {        java.lang.Object ref = userName_;        if (ref instanceof String) {          com.google.protobuf.ByteString b =               com.google.protobuf.ByteString.copyFromUtf8(                  (java.lang.String) ref);          userName_ = b;          return b;        } else {          return (com.google.protobuf.ByteString) ref;        }      }      /**       * <code>required string userName = 2;</code>       */      public Builder setUserName(          java.lang.String value) {        if (value =http://www.mamicode.com/= null) {"";      /**       * <code>required string Password = 3;</code>       */      public boolean hasPassword() {        return ((bitField0_ & 0x00000004) == 0x00000004);      }      /**       * <code>required string Password = 3;</code>       */      public java.lang.String getPassword() {        java.lang.Object ref = password_;        if (!(ref instanceof java.lang.String)) {          java.lang.String s = ((com.google.protobuf.ByteString) ref)              .toStringUtf8();          password_ = s;          return s;        } else {          return (java.lang.String) ref;        }      }      /**       * <code>required string Password = 3;</code>       */      public com.google.protobuf.ByteString          getPasswordBytes() {        java.lang.Object ref = password_;        if (ref instanceof String) {          com.google.protobuf.ByteString b =               com.google.protobuf.ByteString.copyFromUtf8(                  (java.lang.String) ref);          password_ = b;          return b;        } else {          return (com.google.protobuf.ByteString) ref;        }      }      /**       * <code>required string Password = 3;</code>       */      public Builder setPassword(          java.lang.String value) {        if (value =http://www.mamicode.com/= null) {"\n\nUser.proto\022\005netty\"G\n\004User\022\n\n\002ID\030\001 \002(\005\022" +      "\020\n\010userName\030\002 \002(\t\022\020\n\010Password\030\003 \002(\t\022\017\n\007a" +      "ddress\030\004 \003(\tB\027\n\nmyprotobufB\tUserProto"    };    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_netty_User_descriptor =            getDescriptor().getMessageTypes().get(0);          internal_static_netty_User_fieldAccessorTable = new            com.google.protobuf.GeneratedMessage.FieldAccessorTable(              internal_static_netty_User_descriptor,              new java.lang.String[] { "ID", "UserName", "Password", "Address", });          return null;        }      };    com.google.protobuf.Descriptors.FileDescriptor      .internalBuildGeneratedFileFrom(descriptorData,        new com.google.protobuf.Descriptors.FileDescriptor[] {        }, assigner);  }  // @@protoc_insertion_point(outer_class_scope)}

 

3.测试类:

package myprotobuf;import java.util.ArrayList;import java.util.List;import com.google.protobuf.InvalidProtocolBufferException;public class Test {    private static byte[] encode(UserProto.User user) {        return user.toByteArray();    }    private static UserProto.User decode(byte[] body)            throws InvalidProtocolBufferException {        return UserProto.User.parseFrom(body);    }    public static void main(String[] args)            throws InvalidProtocolBufferException {        UserProto.User.Builder builder = UserProto.User.newBuilder();        builder.setID(1);        builder.setUserName("Lilinfeng");        builder.setPassword("Netty Book");        List<String> address = new ArrayList<String>();        address.add("NanJing YuHuaTai");        address.add("BeiJing LiuLiChang");        address.add("ShenZhen HongShuLin");        builder.addAllAddress(address);        UserProto.User user = builder.build();        System.out.println("Before encode : " + user.toString());        UserProto.User user2 = decode(encode(user));        System.out.println("After decode : " + user2.toString());        System.out.println("Assert equal : --> " + user2.equals(user));    }}

 

4.测试结果,说明编码和解密后结果一致:

Before encode : ID: 1userName: "Lilinfeng"Password: "Netty Book"address: "NanJing YuHuaTai"address: "BeiJing LiuLiChang"address: "ShenZhen HongShuLin"After decode : ID: 1userName: "Lilinfeng"Password: "Netty Book"address: "NanJing YuHuaTai"address: "BeiJing LiuLiChang"address: "ShenZhen HongShuLin"Assert equal : --> true

 

google protobuf 简单实例