英文:
How to hook into protobuf java code generation?
问题
在调用protoc
时,是否有一种方式可以钩入Java类的生成过程?我知道可以为protoc
创建插件,但据我了解,只能在那里生成附加文件。我想要做的是根据protobuf模式中的某些选项向Java类添加额外的代码。
因此,对于以下模式:
syntax = "proto3";
import "google/protobuf/descriptor.proto";
enum DateFormat {
LOCAL_DATE = 0;
LOCAL_DATE_TIME = 1;
}
extend google.protobuf.FieldOptions {
DateFormat format = 95765;
}
message MyMessage {
string name = 1;
sint64 id = 2;
string dateTimeField = 3 [(format) = LOCAL_DATE_TIME];
}
我希望在生成的Java类中,dateTimeField
是LocalDateTime
类型,其中包含已解析的日期时间。
英文:
Is there any way to hook into the generation of java classes when invoking protoc
? I know there are plugins which can be created for protoc but as far as I understood it is only possible to generate additional files there. What I would like to do is adding additional code into the java classes based on some options in the protobuf schemas.
So for the following schema:
syntax = "proto3";
import "google/protobuf/descriptor.proto";
enum DateFormat {
LOCAL_DATE = 0;
LOCAL_DATE_TIME = 1;
}
extend google.protobuf.FieldOptions {
DateFormat format = 95765;
}
message MyMessage {
string name = 1;
sint64 id = 2;
string dateTimeField = 3 [(format) = LOCAL_DATE_TIME];
}
I would like to have the dateTimeField
in the generated java class of type LocalDateTime
which contains the already parsed date time.
答案1
得分: 1
我最终找到了一个解决方案。插件不仅可以创建新文件,还可以使用插入点来扩展由Java代码生成器生成的类,详见 https://protobuf.dev/reference/java/java-generated/#plugins。
有一篇很棒的文章详细描述了如何创建一个使用这些插入点的插件。
英文:
I finally found a solution for this. Plugins can not only create new files, but also use insertion points to extend classes generated by the java code generator, see https://protobuf.dev/reference/java/java-generated/#plugins.
There is a great article which describes exactly how to create a plugin which uses those insertion points.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论