您当前的位置: 首页 >  I.T10001 Java

protobuf生成java代码

I.T10001 发布时间:2020-01-10 09:17:18 ,浏览量:4

protobuf官方包下载:https://github.com/protocolbuffers/protobuf/releases/tag/v3.11.1

1、Idea中安装protobuf插件,重启Idea

2、idea中新建maven项目protobuf-demo

3、pom.xml中添加如下依赖

    UTF-8             com.google.protobuf         protobuf-java         3.6.1                 junit         junit         4.13         test                             kr.motd.maven             os-maven-plugin             1.4.1.Final                                     org.xolstice.maven.plugins             protobuf-maven-plugin             0.5.0                                                 com.google.protobuf:protoc:3.1.0:exe:${os.detected.classifier}                                 grpc-java                                                                                     compile                         compile-custom                                                            

4、在idea中编写proto文件,目录结构如下

 

内容如下:

syntax = "proto3";
option java_package = "com.black.model";
option java_outer_classname = "PersonModel";
message Person {
    int32 id = 1;
    string name = 2;
    string email = 3;
}
5、生成java

 

6、测试代码

public class PersonModelTest {
    public static void main(String[] args) throws InvalidProtocolBufferException {
        PersonModel.Person.Builder builder= PersonModel.Person.newBuilder();
        builder.setId(1);
        builder.setEmail("lee@sunvalley.com.cn");
        builder.setName("lee");

        PersonModel.Person person= builder.build();
        System.out.print("====before===="+person);
        System.out.println("==================");
        for(Byte b:person.toByteArray()){
            System.out.print(b);
        }
        System.out.println("==================");
        byte[] byteArray= person.toByteArray();
        PersonModel.Person p2 = PersonModel.Person.parseFrom(byteArray);
        System.out.println("=========反序列化生成对象,转换之后==========");
        System.out.println(p2.getId()+","+p2.getEmail()+","+p2.getName());
    }
}
关注
打赏
1688896170
查看更多评论

I.T10001

暂无认证

  • 4浏览

    0关注

    154博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0467s