protobuf-Java使用.md

protobuf 环境配置

1、安装编译器

下载地址

直接解压缩。

2、配置环境变量

环境变量Path 中增加安装目录的路径

3、检查是否配置成功

protoc
Usage: protoc [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:-IPATH, --proto_path=PATH   Specify the directory in which to search forimports.  May be specified multiple times;directories will be searched in order.  If notgiven, the current working directory is used.If not found in any of the these directories,the --descriptor_set_in descriptors will bechecked for required proto file.--version                   #版本-h, --help                  #帮助--encode=MESSAGE_TYPE       Read a text-format message of the given typefrom standard input and write it in binaryto standard output.  The message type mustbe defined in PROTO_FILES or their imports.--deterministic_output      When using --encode, ensure map fields aredeterministically ordered. Note that this orderis not canonical, and changes across builds orreleases of protoc.--decode=MESSAGE_TYPE       Read a binary message of the given type fromstandard input and write it in text formatto standard output.  The message type mustbe defined in PROTO_FILES or their imports.--decode_raw                Read an arbitrary protocol message fromstandard input and write the raw tag/valuepairs in text format to standard output.  NoPROTO_FILES should be given when using thisflag.--descriptor_set_in=FILES   Specifies a delimited list of FILESeach containing a FileDescriptorSet (aprotocol buffer defined in descriptor.proto).The FileDescriptor for each of the PROTO_FILESprovided will be loaded from theseFileDescriptorSets. If a FileDescriptorappears multiple times, the first occurrencewill be used.-oFILE,                     Writes a FileDescriptorSet (a protocol buffer,--descriptor_set_out=FILE defined in descriptor.proto) containing all ofthe input files to FILE.--include_imports           When using --descriptor_set_out, also includeall dependencies of the input files in theset, so that the set is self-contained.--include_source_info       When using --descriptor_set_out, do not stripSourceCodeInfo from the FileDescriptorProto.This results in vastly larger descriptors thatinclude information about the originallocation of each decl in the source file aswell as surrounding comments.--retain_options            When using --descriptor_set_out, do not stripany options from the FileDescriptorProto.This results in potentially larger descriptorsthat include information about options that wereonly meant to be useful during compilation.--dependency_out=FILE       Write a dependency output file in the formatexpected by make. This writes the transitiveset of input file paths to FILE--error_format=FORMAT       Set the format in which to print errors.FORMAT may be 'gcc' (the default) or 'msvs'(Microsoft Visual Studio format).--fatal_warnings            Make warnings be fatal (similar to -Werr ingcc). This flag will make protoc returnwith a non-zero exit code if any warningsare generated.--print_free_field_numbers  Print the free field numbers of the messagesdefined in the given proto files. Extension rangesare counted as occupied fields numbers.--enable_codegen_trace      Enables tracing which parts of protoc areresponsible for what codegen output. Not supportedby all backends or on all platforms.--plugin=EXECUTABLE         Specifies a plugin executable to use.Normally, protoc searches the PATH forplugins, but you may specify additionalexecutables not in the path using this flag.Additionally, EXECUTABLE may be of the formNAME=PATH, in which case the given plugin nameis mapped to the given executable even ifthe executable's own name differs.--cpp_out=OUT_DIR           Generate C++ header and source.--csharp_out=OUT_DIR        Generate C# source file.--java_out=OUT_DIR          Generate Java source file.--kotlin_out=OUT_DIR        Generate Kotlin file.--objc_out=OUT_DIR          Generate Objective-C header and source.--php_out=OUT_DIR           Generate PHP source file.--pyi_out=OUT_DIR           Generate python pyi stub.--python_out=OUT_DIR        Generate Python source file.--ruby_out=OUT_DIR          Generate Ruby source file.--rust_out=OUT_DIR          Generate Rust sources.@<filename>                 Read options and filenames from file. If arelative file path is specified, the filewill be searched in the working directory.The --proto_path option will not affect howthis argument file is searched. Content ofthe file will be expanded in the position of@<filename> as in the argument list. Notethat shell expansion is not applied to thecontent of the file (i.e., you cannot usequotes, wildcards, escapes, commands, etc.).Each line corresponds to a single argument,even if it contains spaces.
E:\setups\protoc-25.0-win64\bin\protoc.exe --java_out=E:\projects_study\research\base\target Data2.proto 

idea 中使用 protobuf

1、idea 安装 protobuf 相关插件

安装插件:

  • protobuf generator:根据 .proto 文件来生成 proto 对象
  • pojo to proto:类文件-右键-PojoProto, 将简单Java类型转成proto message拷贝至剪贴板

2、配置全局 protobuf

image-20240119192758808

人工生成Java文件

1、引入包

        <!--  protobuf 支持 Java 核心包--><dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java</artifactId><version>3.21.11</version></dependency><!--  proto 与 Json 互转会用到--><dependency><groupId>com.google.protobuf</groupId><artifactId>protobuf-java-util</artifactId><version>3.15.3</version></dependency>

2、编写.proto文件

//使用 proto3 语法 ,未指定则使用proto2
syntax = "proto3";//生成 proto 文件所在包路径
package demon.research.proto;//生成的 proto 文件所在包路径
option java_package = "demon.research.proto";//生成的 proto 文件名
option java_outer_classname="DataGen";//message关键字 定义一个消息体。
message DataOriginal{int32 id = 1;string code = 2;string name = 3;
}

3、生成Java 文件

直接在文件上点击右键,quick gen protobuf here,则在此目录根据包生成一个java文件,名字为Data.java.

quick gen protobuf rules 则根据配置的规则,把java文件生成在指定的目录。

然后把生成的Java文件,copy到java类目录下

4、序列化和反序列化

        //初始化数据DataGen.DataOriginal.Builder builder = DataGen.DataOriginal.newBuilder();builder.setId(1).setCode("001").setName("张三").build();//序列化DataGen.DataOriginal build = builder.build();//转换成字节数组byte[] s = build.toByteArray();System.out.println("protobuf数据bytes[]:" + Arrays.toString(s));System.out.println("protobuf序列化大小: " + s.length);DataGen.DataOriginal data = null;String jsonObject = null;try {//反序列化data = DataGen.DataOriginal.parseFrom(s);//转 jsonjsonObject = JsonFormat.printer().print(data);} catch (Exception e) {e.printStackTrace();}System.out.println("Json格式化结果:\n" + jsonObject);System.out.println("Json格式化数据大小: " + jsonObject.getBytes().length);

输出结果:

protobuf数据bytes[]:[8, 1, 18, 3, 48, 48, 49, 26, 6, -27, -68, -96, -28, -72, -119]
protobuf序列化大小: 15
Json格式化结果:
{"id": 1,"code": "001","name": "张三"
}
Json格式化数据大小: 50

传输的数据,确实比json格式的要小。

maven自动生成

引入插件

        <extensions><extension><groupId>kr.motd.maven</groupId><artifactId>os-maven-plugin</artifactId><version>1.5.0.Final</version></extension></extensions><plugin><groupId>org.xolstice.maven.plugins</groupId><artifactId>protobuf-maven-plugin</artifactId><version>0.6.1</version><configuration><protocArtifact>com.google.protobuf:protoc:3.21.11:exe:${os.detected.classifier}</protocArtifact><pluginId>grpc-java</pluginId><pluginArtifact>io.grpc:protoc-gen-grpc-java:3.21.11:exe:${os.detected.classifier}</pluginArtifact></configuration><executions><execution><goals><goal>compile</goal><goal>compile-custom</goal></goals></execution></executions></plugin>

默认.proto文件的扫描目录为: ${basedir}/src/main/proto

默认生成的文件路径为:${project.build.directory}/generated-sources/protobuf/java.

需要人工把代码放到指定目录。如果需要自动生成到指定目录,则修改指定目录。

注意:默认会把指定的目录数据都给删除掉。,可以设置clearOutputDirectory为false。

附录

参考

下载地址

生成代码

// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: DataOriginal.proto// Protobuf Java Version: 3.25.0// java_package  设置的包名
package demon.research.proto;//java_outer_classname 指定的类名
public final class DataGen {//避免修改private DataGen() {}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 DataOriginalOrBuilder extends// @@protoc_insertion_point(interface_extends:demon.research.proto.DataOriginal)com.google.protobuf.MessageOrBuilder {/*** <code>int32 id = 1;</code>* @return The id.*/int getId();//******************* 会为字符串类型 生成序列化 方法。/*** <code>string code = 2;</code>* @return The code.*/String getCode();/*** <code>string code = 2;</code>* @return The bytes for code.*/com.google.protobuf.ByteStringgetCodeBytes();/*** <code>string name = 3;</code>* @return The name.*/String getName();/*** <code>string name = 3;</code>* @return The bytes for name.*/com.google.protobuf.ByteStringgetNameBytes();}/*** <pre>*message关键字 定义一个消息体。* </pre>** Protobuf type {@code demon.research.proto.DataOriginal}*/public static final class DataOriginal extendscom.google.protobuf.GeneratedMessageV3 implements// @@protoc_insertion_point(message_implements:demon.research.proto.DataOriginal)DataOriginalOrBuilder {private static final long serialVersionUID = 0L;// Use DataOriginal.newBuilder() to construct.private DataOriginal(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {super(builder);}private DataOriginal() {code_ = "";name_ = "";}@Override@SuppressWarnings({"unused"})protected Object newInstance(UnusedPrivateParameter unused) {return new DataOriginal();}public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return DataGen.internal_static_demon_research_proto_DataOriginal_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return DataGen.internal_static_demon_research_proto_DataOriginal_fieldAccessorTable.ensureFieldAccessorsInitialized(DataOriginal.class, Builder.class);}public static final int ID_FIELD_NUMBER = 1;private int id_ = 0;/*** <code>int32 id = 1;</code>* @return The id.*/@Overridepublic int getId() {return id_;}public static final int CODE_FIELD_NUMBER = 2;@SuppressWarnings("serial")private volatile Object code_ = "";/*** <code>string code = 2;</code>* @return The code.*/@Overridepublic String getCode() {Object ref = code_;if (ref instanceof String) {return (String) ref;} else {com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();code_ = s;return s;}}/*** <code>string code = 2;</code>* @return The bytes for code.*/@Overridepublic com.google.protobuf.ByteStringgetCodeBytes() {Object ref = code_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);code_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}public static final int NAME_FIELD_NUMBER = 3;@SuppressWarnings("serial")private volatile Object name_ = "";/*** <code>string name = 3;</code>* @return The name.*/@Overridepublic 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();name_ = s;return s;}}/*** <code>string name = 3;</code>* @return The bytes for name.*/@Overridepublic com.google.protobuf.ByteStringgetNameBytes() {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;}}private byte memoizedIsInitialized = -1;@Overridepublic final boolean isInitialized() {byte isInitialized = memoizedIsInitialized;if (isInitialized == 1) return true;if (isInitialized == 0) return false;memoizedIsInitialized = 1;return true;}@Overridepublic void writeTo(com.google.protobuf.CodedOutputStream output)throws java.io.IOException {if (id_ != 0) {output.writeInt32(1, id_);}if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(code_)) {com.google.protobuf.GeneratedMessageV3.writeString(output, 2, code_);}if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {com.google.protobuf.GeneratedMessageV3.writeString(output, 3, name_);}getUnknownFields().writeTo(output);}@Overridepublic int getSerializedSize() {int size = memoizedSize;if (size != -1) return size;size = 0;if (id_ != 0) {size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, id_);}if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(code_)) {size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, code_);}if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, name_);}size += getUnknownFields().getSerializedSize();memoizedSize = size;return size;}@Overridepublic boolean equals(final Object obj) {if (obj == this) {return true;}if (!(obj instanceof DataOriginal)) {return super.equals(obj);}DataOriginal other = (DataOriginal) obj;if (getId()!= other.getId()) return false;if (!getCode().equals(other.getCode())) return false;if (!getName().equals(other.getName())) return false;if (!getUnknownFields().equals(other.getUnknownFields())) return false;return true;}@Overridepublic int hashCode() {if (memoizedHashCode != 0) {return memoizedHashCode;}int hash = 41;hash = (19 * hash) + getDescriptor().hashCode();hash = (37 * hash) + ID_FIELD_NUMBER;hash = (53 * hash) + getId();hash = (37 * hash) + CODE_FIELD_NUMBER;hash = (53 * hash) + getCode().hashCode();hash = (37 * hash) + NAME_FIELD_NUMBER;hash = (53 * hash) + getName().hashCode();hash = (29 * hash) + getUnknownFields().hashCode();memoizedHashCode = hash;return hash;}public static DataOriginal parseFrom(java.nio.ByteBuffer data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static DataOriginal parseFrom(java.nio.ByteBuffer data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static DataOriginal parseFrom(com.google.protobuf.ByteString data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static DataOriginal parseFrom(com.google.protobuf.ByteString data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static DataOriginal parseFrom(byte[] data)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data);}public static DataOriginal parseFrom(byte[] data,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {return PARSER.parseFrom(data, extensionRegistry);}public static DataOriginal parseFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static DataOriginal 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 DataOriginal parseDelimitedFrom(java.io.InputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);}public static DataOriginal 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 DataOriginal parseFrom(com.google.protobuf.CodedInputStream input)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);}public static DataOriginal parseFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);}@Overridepublic Builder newBuilderForType() { return newBuilder(); }public static Builder newBuilder() {return DEFAULT_INSTANCE.toBuilder();}public static Builder newBuilder(DataOriginal prototype) {return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);}@Overridepublic Builder toBuilder() {return this == DEFAULT_INSTANCE? new Builder() : new Builder().mergeFrom(this);}@Overrideprotected Builder newBuilderForType(BuilderParent parent) {Builder builder = new Builder(parent);return builder;}/*** <pre>*message关键字 定义一个消息体。* </pre>** Protobuf type {@code demon.research.proto.DataOriginal}*/public static final class Builder extendscom.google.protobuf.GeneratedMessageV3.Builder<Builder> implements// @@protoc_insertion_point(builder_implements:demon.research.proto.DataOriginal)DataOriginalOrBuilder {public static final com.google.protobuf.Descriptors.DescriptorgetDescriptor() {return DataGen.internal_static_demon_research_proto_DataOriginal_descriptor;}@Overrideprotected FieldAccessorTableinternalGetFieldAccessorTable() {return DataGen.internal_static_demon_research_proto_DataOriginal_fieldAccessorTable.ensureFieldAccessorsInitialized(DataOriginal.class, Builder.class);}// Construct using demon.research.proto.DataGen.DataOriginal.newBuilder()private Builder() {}private Builder(BuilderParent parent) {super(parent);}@Overridepublic Builder clear() {super.clear();bitField0_ = 0;id_ = 0;code_ = "";name_ = "";return this;}@Overridepublic com.google.protobuf.Descriptors.DescriptorgetDescriptorForType() {return DataGen.internal_static_demon_research_proto_DataOriginal_descriptor;}@Overridepublic DataOriginal getDefaultInstanceForType() {return DataOriginal.getDefaultInstance();}@Overridepublic DataOriginal build() {DataOriginal result = buildPartial();if (!result.isInitialized()) {throw newUninitializedMessageException(result);}return result;}@Overridepublic DataOriginal buildPartial() {DataOriginal result = new DataOriginal(this);if (bitField0_ != 0) { buildPartial0(result); }onBuilt();return result;}private void buildPartial0(DataOriginal result) {int from_bitField0_ = bitField0_;if (((from_bitField0_ & 0x00000001) != 0)) {result.id_ = id_;}if (((from_bitField0_ & 0x00000002) != 0)) {result.code_ = code_;}if (((from_bitField0_ & 0x00000004) != 0)) {result.name_ = name_;}}@Overridepublic Builder clone() {return super.clone();}@Overridepublic Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return super.setField(field, value);}@Overridepublic Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {return super.clearField(field);}@Overridepublic Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {return super.clearOneof(oneof);}@Overridepublic Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,int index, Object value) {return super.setRepeatedField(field, index, value);}@Overridepublic Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field,Object value) {return super.addRepeatedField(field, value);}@Overridepublic Builder mergeFrom(com.google.protobuf.Message other) {if (other instanceof DataOriginal) {return mergeFrom((DataOriginal)other);} else {super.mergeFrom(other);return this;}}public Builder mergeFrom(DataOriginal other) {if (other == DataOriginal.getDefaultInstance()) return this;if (other.getId() != 0) {setId(other.getId());}if (!other.getCode().isEmpty()) {code_ = other.code_;bitField0_ |= 0x00000002;onChanged();}if (!other.getName().isEmpty()) {name_ = other.name_;bitField0_ |= 0x00000004;onChanged();}this.mergeUnknownFields(other.getUnknownFields());onChanged();return this;}@Overridepublic final boolean isInitialized() {return true;}@Overridepublic Builder mergeFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws java.io.IOException {if (extensionRegistry == null) {throw new NullPointerException();}try {boolean done = false;while (!done) {int tag = input.readTag();switch (tag) {case 0:done = true;break;case 8: {id_ = input.readInt32();bitField0_ |= 0x00000001;break;} // case 8case 18: {code_ = input.readStringRequireUtf8();bitField0_ |= 0x00000002;break;} // case 18case 26: {name_ = input.readStringRequireUtf8();bitField0_ |= 0x00000004;break;} // case 26default: {if (!super.parseUnknownField(input, extensionRegistry, tag)) {done = true; // was an endgroup tag}break;} // default:} // switch (tag)} // while (!done)} catch (com.google.protobuf.InvalidProtocolBufferException e) {throw e.unwrapIOException();} finally {onChanged();} // finallyreturn this;}private int bitField0_;private int id_ ;/*** <code>int32 id = 1;</code>* @return The id.*/@Overridepublic int getId() {return id_;}/*** <code>int32 id = 1;</code>* @param value The id to set.* @return This builder for chaining.*/public Builder setId(int value) {id_ = value;bitField0_ |= 0x00000001;onChanged();return this;}/*** <code>int32 id = 1;</code>* @return This builder for chaining.*/public Builder clearId() {bitField0_ = (bitField0_ & ~0x00000001);id_ = 0;onChanged();return this;}private Object code_ = "";/*** <code>string code = 2;</code>* @return The code.*/public String getCode() {Object ref = code_;if (!(ref instanceof String)) {com.google.protobuf.ByteString bs =(com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();code_ = s;return s;} else {return (String) ref;}}/*** <code>string code = 2;</code>* @return The bytes for code.*/public com.google.protobuf.ByteStringgetCodeBytes() {Object ref = code_;if (ref instanceof String) {com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);code_ = b;return b;} else {return (com.google.protobuf.ByteString) ref;}}/*** <code>string code = 2;</code>* @param value The code to set.* @return This builder for chaining.*/public Builder setCode(String value) {if (value == null) { throw new NullPointerException(); }code_ = value;bitField0_ |= 0x00000002;onChanged();return this;}/*** <code>string code = 2;</code>* @return This builder for chaining.*/public Builder clearCode() {code_ = getDefaultInstance().getCode();bitField0_ = (bitField0_ & ~0x00000002);onChanged();return this;}/*** <code>string code = 2;</code>* @param value The bytes for code to set.* @return This builder for chaining.*/public Builder setCodeBytes(com.google.protobuf.ByteString value) {if (value == null) { throw new NullPointerException(); }checkByteStringIsUtf8(value);code_ = value;bitField0_ |= 0x00000002;onChanged();return this;}private Object name_ = "";/*** <code>string name = 3;</code>* @return The name.*/public String getName() {Object ref = name_;if (!(ref instanceof String)) {com.google.protobuf.ByteString bs =(com.google.protobuf.ByteString) ref;String s = bs.toStringUtf8();name_ = s;return s;} else {return (String) ref;}}/*** <code>string name = 3;</code>* @return The bytes for name.*/public com.google.protobuf.ByteStringgetNameBytes() {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>string name = 3;</code>* @param value The name to set.* @return This builder for chaining.*/public Builder setName(String value) {if (value == null) { throw new NullPointerException(); }name_ = value;bitField0_ |= 0x00000004;onChanged();return this;}/*** <code>string name = 3;</code>* @return This builder for chaining.*/public Builder clearName() {name_ = getDefaultInstance().getName();bitField0_ = (bitField0_ & ~0x00000004);onChanged();return this;}/*** <code>string name = 3;</code>* @param value The bytes for name to set.* @return This builder for chaining.*/public Builder setNameBytes(com.google.protobuf.ByteString value) {if (value == null) { throw new NullPointerException(); }checkByteStringIsUtf8(value);name_ = value;bitField0_ |= 0x00000004;onChanged();return this;}@Overridepublic final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.setUnknownFields(unknownFields);}@Overridepublic final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {return super.mergeUnknownFields(unknownFields);}// @@protoc_insertion_point(builder_scope:demon.research.proto.DataOriginal)}// @@protoc_insertion_point(class_scope:demon.research.proto.DataOriginal)private static final DataOriginal DEFAULT_INSTANCE;static {DEFAULT_INSTANCE = new DataOriginal();}public static DataOriginal getDefaultInstance() {return DEFAULT_INSTANCE;}private static final com.google.protobuf.Parser<DataOriginal>PARSER = new com.google.protobuf.AbstractParser<DataOriginal>() {@Overridepublic DataOriginal parsePartialFrom(com.google.protobuf.CodedInputStream input,com.google.protobuf.ExtensionRegistryLite extensionRegistry)throws com.google.protobuf.InvalidProtocolBufferException {Builder builder = newBuilder();try {builder.mergeFrom(input, extensionRegistry);} catch (com.google.protobuf.InvalidProtocolBufferException e) {throw e.setUnfinishedMessage(builder.buildPartial());} catch (com.google.protobuf.UninitializedMessageException e) {throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());} catch (java.io.IOException e) {throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(builder.buildPartial());}return builder.buildPartial();}};public static com.google.protobuf.Parser<DataOriginal> parser() {return PARSER;}@Overridepublic com.google.protobuf.Parser<DataOriginal> getParserForType() {return PARSER;}@Overridepublic DataOriginal getDefaultInstanceForType() {return DEFAULT_INSTANCE;}}private static final com.google.protobuf.Descriptors.Descriptorinternal_static_demon_research_proto_DataOriginal_descriptor;private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTableinternal_static_demon_research_proto_DataOriginal_fieldAccessorTable;public static com.google.protobuf.Descriptors.FileDescriptorgetDescriptor() {return descriptor;}private static  com.google.protobuf.Descriptors.FileDescriptordescriptor;static {String[] descriptorData = {"\n\022DataOriginal.proto\022\024demon.research.pro" +"to\"6\n\014DataOriginal\022\n\n\002id\030\001 \001(\005\022\014\n\004code\030\002" +" \001(\t\022\014\n\004name\030\003 \001(\tB\037\n\024demon.research.pro" +"toB\007DataGenb\006proto3"};descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData,new com.google.protobuf.Descriptors.FileDescriptor[] {});internal_static_demon_research_proto_DataOriginal_descriptor =getDescriptor().getMessageTypes().get(0);internal_static_demon_research_proto_DataOriginal_fieldAccessorTable = newcom.google.protobuf.GeneratedMessageV3.FieldAccessorTable(internal_static_demon_research_proto_DataOriginal_descriptor,new String[] { "Id", "Code", "Name", });}// @@protoc_insertion_point(outer_class_scope)
}

1、DataGen 类只提供框架方法。

public final class DataGen {private DataGen() {}public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);}private static final com.google.protobuf.Descriptors.Descriptorinternal_static_demon_research_proto_DataOriginal_descriptor;private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTableinternal_static_demon_research_proto_DataOriginal_fieldAccessorTable;public static com.google.protobuf.Descriptors.FileDescriptorgetDescriptor() {return descriptor;}private static  com.google.protobuf.Descriptors.FileDescriptordescriptor;

2、接口 DataOriginalOrBuilder,只提供了get方法。

int getId();
String getCode();
com.google.protobuf.ByteString         getCodeBytes();
String getName();com.google.protobuf.ByteString          getNameBytes();

3、类DataOriginal 继承类 com.google.protobuf.GeneratedMessageV3 ,实现接口 DataOriginalOrBuilder提供了get方法,并保存了数据。同时提供了序列化与反序列化能力

   public static final int ID_FIELD_NUMBER = 1;private int id_ = 0;/*** <code>int32 id = 1;</code>* @return The id.*/@Overridepublic int getId() {return id_;}

4、类Builder 继承类 com.google.protobuf.GeneratedMessageV3.Builder<Builder> ,实现接口 DataOriginalOrBuilder提供了get/set方法,

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/637988.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

cmake-动态库和静态库及使用OpenCV第三方库

文章目录 静态库准备的文件CMakeLists文件使用静态库 动态库准备的文件CMakeLists文件使用动态库 使用OpenCV库 项目中会有单个源文件构建的多个可执行文件的可能。项目中有多个源文件&#xff0c;通常分布在不同子目录中。这种实践有助于项目的源代码结构&#xff0c;而且支持…

《WebKit 技术内幕》之五(2): HTML解释器和DOM 模型

2.HTML 解释器 2.1 解释过程 HTML 解释器的工作就是将网络或者本地磁盘获取的 HTML 网页和资源从字节流解释成 DOM 树结构。 这一过程中&#xff0c;WebKit 内部对网页内容在各个阶段的结构表示。 WebKit 中这一过程如下&#xff1a;首先是字节流&#xff0c;经过解码之…

某马头条——day07

APP端搜索 搭建ES环境 docker pull elasticsearch:7.4.0 docker run -id --name elasticsearch -d --restartalways -p 9200:9200 -p 9300:9300 -v /usr/share/elasticsearch/plugins:/usr/share/elasticsearch/plugins -e "discovery.typesingle-node" elasticsear…

如何通过frp、geoserver发布家里电脑的空间数据教程

如何通过家里电脑的geoserver发布空间数据的教程 简介 大家好&#xff0c;我是锐多宝&#xff0c;最近我在开发一个新网站的时候遇到一个需求&#xff0c;这里记录一下以帮助需要用到的网友。 我的需求是&#xff1a;用户通过网站前端上传空间数据后&#xff0c;即可在前端展…

视频监控需求记录

记录一下最近要做的需求&#xff0c;我个人任务还是稍微比较复杂的 需求&#xff1a;需要实现一个视频实时监控、视频回放、视频设备管理&#xff0c;以上都是与组织架构有关 大概的界面长这个样子 听着需求好像很简单&#xff0c;但是~我们需要在一个界面上显示两个厂商的视…

第四十周:文献阅读+GAN

目录 摘要 Abstract 文献阅读&#xff1a;结合小波变换和主成分分析的长短期记忆神经网络深度学习在城市日需水量预测中的应用 现有问题 创新点 方法论 PCA&#xff08;主要成分分析法&#xff09; DWT&#xff08;离散小波变换&#xff09; DWT-PCA-LSTM模型 研究实…

【Docker】在Windows操作系统安装Docker前配置环境

欢迎来到《小5讲堂》&#xff0c;大家好&#xff0c;我是全栈小5。 这是《Docker容器》序列文章&#xff0c;每篇文章将以博主理解的角度展开讲解&#xff0c; 特别是针对知识点的概念进行叙说&#xff0c;大部分文章将会对这些概念进行实际例子验证&#xff0c;以此达到加深对…

139基于matlab多旅行商MTSP问题

基于matlab多旅行商MTSP问题&#xff0c;利用遗传算法求解多旅行商问题的算法设计&#xff0c;输出MTSP路径。相互独立路径&#xff0c;同一起点路径。程序已调通&#xff0c;可直接运行。 139 matlab多旅行熵M-TSP (xiaohongshu.com)https://www.xiaohongshu.com/explore/65ab…

浅谈 ret2text

文章目录 ret2text无需传参重构传参函数调用约定x86x64 ret2text ret2text就是执行程序中已有的代码&#xff0c;例如程序中写有system等系统的调用函数 无需传参 如果程序的后门函数参数已经满足 getshell 的需求&#xff0c;那么就可以直接溢出覆盖 ret 地址不用考虑传参问…

2024最新 8 款电脑数据恢复软件推荐分享

数据恢复是一个涉及从设备硬盘驱动器检索已删除文件的过程。这可能需要存储在工作站、笔记本电脑、移动设备、服务器、相机、闪存驱动器上的数据——任何在独立或镜像/阵列驱动器上存储数据的东西&#xff0c;无论是内部还是外部。 在某些情况下&#xff0c;文件可能被意外或故…

AtCoder Beginner Contest 337 (ABCDEG题)

A - Scoreboard Problem Statement Team Takahashi and Team Aoki played N N N matches. In the i i i-th match ( 1 ≤ i ≤ N ) (1\leq i\leq N) (1≤i≤N), Team Takahashi scored X i X _ i Xi​ points, and Team Aoki scored Y i Y _ i Yi​ points. The team wi…

大数据关联规则挖掘:Apriori算法的深度探讨

文章目录 大数据关联规则挖掘&#xff1a;Apriori算法的深度探讨一、简介什么是关联规则挖掘&#xff1f;什么是频繁项集&#xff1f;什么是支持度与置信度&#xff1f;Apriori算法的重要性应用场景 二、理论基础项和项集支持度&#xff08;Support&#xff09;置信度&#xff…

第135期 一周游历(上)(20240120)

数据库管理135期 2024-01-20 第135期 一周游历(上)&#xff08;20240120&#xff09;1 PolarDB开发者大会2 工作3 Oracle甲骨文4 Oracle ACE总结 第135期 一周游历(上)&#xff08;20240120&#xff09; 作者&#xff1a;胖头鱼的鱼缸&#xff08;尹海文&#xff09; Oracle AC…

JS-WebAPIs-本地存储(五)

• 本地存储介绍 以前我们页面写的数据一刷新页面就没有了&#xff0c;是不是&#xff1f;随着互联网的快速发展&#xff0c;基于网页的应用越来越普遍&#xff0c;同时也变的越来越复杂&#xff0c;为了满足各种各样的需求&#xff0c;会经常 性在本地存储大量的数据&#xf…

运筹说 第107期 | 排队论创始人——阿格纳·克拉鲁普·爱尔朗

前面我们已经了解了非线性规划的相关内容&#xff0c;相信大家一定也有所收获&#xff0c;下面我们将带着大家继续了解排队论的相关内容&#xff0c;在本次文章中我们将一起走近排队论的奠基人——阿格纳克拉鲁普爱尔朗&#xff08;Agner Krarup Erlang&#xff09;&#xff0c…

基于Elasticsearch+Logstash+Kibana+Filebeat的日志收集分析及可视化

sudo rm /var/lib/dpkg/lock* sudo dpkg --configure -a apt update tail -f /var/log/car.log 1.1、项目概述 海量的业务应用&#xff0c;也带来了海量的日志数据&#xff0c;给业务应用的运维带来了新的挑战。例如&#xff0c;我们常用的网约车应用&#xff0c;单个平台…

I.MX8QM EC20适配

Android SDK&#xff1a;imx8_13.0.0_1.2.0(android 13 u-boot 2022.04 kernel 5.15.74) 一、内核修改 添加PID、VID。在“drivers/usb/serial/option.c”中可以看到EC25的PID和VID已经添加&#xff0c;而且这个EC25的PID和VID与EC20的相同&#xff0c;所以这里可以不用修改…

Traceroute 详解

前言 如果您是网络管理员&#xff0c;系统管理员或任何系统操作团队的一员&#xff0c;那么您可能已经听说过名为TRACEROUTE的工具。默认情况下&#xff0c;它是大多数操作系统中都提供的非常方便的工具。 网络管理员和系统管理员在日常活动中最常使用此工具。它基本上是一个…

二叉树 - 堆 | 数据结构中的小技巧大作用

&#x1f4f7; 江池俊&#xff1a; 个人主页 &#x1f525;个人专栏&#xff1a; ✅数据结构冒险记 ✅C语言进阶之路 &#x1f305; 有航道的人&#xff0c;再渺小也不会迷途。 文章目录 一、堆的概念及介绍二、结构图示三、堆的代码实现&#xff08;图解&#xff09;3.1 创…

HackTheBox - Medium - Linux - Noter

Noter Noter 是一种中型 Linux 机器&#xff0c;其特点是利用了 Python Flask 应用程序&#xff0c;该应用程序使用易受远程代码执行影响的“节点”模块。由于“MySQL”守护进程以用户“root”身份运行&#xff0c;因此可以通过利用“MySQL”的用户定义函数来利用它来获得RCE并…