如何用Java编写自定义Protobuf代码生成器
我正在尝试为内部专有编程语言编写一个自定义代码生成器。我想我可以用Java编写生成器,使用protoc插件指南。我的main()执行以下操作:如何用Java编写自定义Protobuf代码生成器,java,protocol-buffers,protoc,Java,Protocol Buffers,Protoc,我正在尝试为内部专有编程语言编写一个自定义代码生成器。我想我可以用Java编写生成器,使用protoc插件指南。我的main()执行以下操作: public static void main(String[] args) throws IOException { CodeGenerator gen = new CodeGenerator(); PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos
public static void main(String[] args) throws IOException {
CodeGenerator gen = new CodeGenerator();
PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(args[0].getBytes());
codeGeneratorRequest.getProtoFileList().forEach(gen::handleFile);
// get the response and do something with it
//PluginProtos.CodeGeneratorResponse response = PluginProtos.CodeGeneratorResponse.newBuilder().build();
//response.writeTo(System.out);
}
#!/bin/bash
java -cp ./codegen.jar CodeGeneratorMain "$@"
(显然,我才刚刚开始;在实际编写生成逻辑之前,我想先让一些简单的东西工作起来)
问题是:如何使用--plugin参数调用protoc,以使用我的插件生成自定义语言中的代码?我试着编写一个shell脚本,如下所示:
public static void main(String[] args) throws IOException {
CodeGenerator gen = new CodeGenerator();
PluginProtos.CodeGeneratorRequest codeGeneratorRequest = PluginProtos.CodeGeneratorRequest.parseFrom(args[0].getBytes());
codeGeneratorRequest.getProtoFileList().forEach(gen::handleFile);
// get the response and do something with it
//PluginProtos.CodeGeneratorResponse response = PluginProtos.CodeGeneratorResponse.newBuilder().build();
//response.writeTo(System.out);
}
#!/bin/bash
java -cp ./codegen.jar CodeGeneratorMain "$@"
我试着像这样调用protoc:protoc--plugin=protoc gen code--code_out=./build hello.proto
但是,当我运行它时,我得到了以下错误:
线程“main”java.lang.ArrayIndexOutOfBoundsException中出现异常:0
位于codeneratormain.main(codeneratormain.java:12)
--代码:protoc gen代码:插件失败,状态代码为1
好像它根本没有通过stdin上的codeneratorrequest。我该如何证实这一点?我明显做错了什么吗?所以在阅读和重读文档之后,我意识到了我的愚蠢错误:protoc通过stdin而不是argv传递解析后的输入。这意味着如果我更改此选项:
PluginProtos.codeneratorrequest codeneratorrequest=PluginProtos.codeneratorrequest.parseFrom(args[0].getBytes())代码>到此:PluginProtos.codeneratorrequest codeneratorrequest=PluginProtos.codeneratorrequest.parseFrom(System.in)代码>
它可以工作。可能有点OT:如果您只是想生成Java代码,那么可能值得一看,我不想生成Java类。ProtoBufs已经可以生成Java源代码。这是一个用于生成非Java代码的Java插件。您是如何使其工作的。我也在做同样的事情。如何将shell脚本与protoc联系起来。我不断收到错误消息,说程序找不到或不可执行。你能帮我做这个吗?