如何从现有的 protobuf 文件创建 java pojo?

How to create java pojo from the existing protobuf file?

我正在尝试将 .proto(2.5 版)转换为 java pojo。例如

来自

message Article {
    optional string title = 1;
}

public class Article {
    private string title;

    public string getTitle() {
        return title;
    }

    public void setTitle(string title) {
        this.title = title;
    }
}

但是官方协议不支持生成pojo方式java文件。

有没有什么工具可以自动从.proto文件生成pojo?

此 SO 线程包含用于生成协议缓冲区 Java "nano" 变体的文档,这可能正是您正在寻找的内容:Android protobuf nano documentation

否则,最简单的自己生成代码的方法可能是使用google开源协议缓冲区代码生成器为您的协议缓冲区生成“descriptors”,然后迭代描述符(也许使用 java poet 等库)生成 Java 代码。

看看:https://github.com/sagroskin/protoc-gen-pojo

这是使用原型文件"descriptors"

  • 我不保留评论或文档。
  • 没有 getter 或二传手。
  • 每个 .proto 文件输出一个 .java 文件

然而,只要稍加努力,它就可以解决您的用例。

example.proto

syntax = "proto3";

message Article {
    string title = 1;
}

enum yesno {
  no = 0;
  yes = 1;
}
git clone https://github.com/sagroskin/protoc-gen-pojo.git
cd protoc-gen-pojo
go build
# Run protobuf/bin/protoc with this plugin
protoc --plugin=./protoc-gen-pojo --proto_path=./ --pojo_out=./ example.proto

它会创建 example.java

// Code generated by protoc-gen-pojo.

public enum yesno {
    no (0),
    yes (1),
}

public class Article {
    public String title;
}