gradle依赖库:

implementation 'com.google.protobuf:protobuf-java:3.4.0'
implementation 'com.google.protobuf:protobuf-java-util:3.4.0'

  

0.编写.proto文件,编译生成对应Java源文件:

syntax = "proto2";
option java_generic_services = true;
option java_package = "gj.protobuf.sample";
option java_outer_classname = "ProtoSample";

message Student {
    required int32 id = 1;
    optional string name = 2;
}

  

protoc --java_out=..\..\java ProtobufSample.proto

1.编写Java文件:

package gj.protobuf.sample;

import com.google.protobuf.InvalidProtocolBufferException;

/**
 * Author: areful
 */
public class ProtoSampleTest {
    public static void main(String[] args) {
        ProtoSample.Student student = ProtoSample.Student.newBuilder()
                .setId(1)
                .setName("areful")
                .build();
        System.out.println(student);

        byte[] data = student.toByteArray();
        try {
            ProtoSample.Student student1 = ProtoSample.Student.parseFrom(data);
            System.out.println(student1);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
    }
}

    

2.编译运行:

Java中使用Protobuf

 

相关文章:

  • 2021-12-09
  • 2021-08-12
  • 2022-03-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-05
  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2021-11-21
  • 2021-11-15
相关资源
相似解决方案