如何钩入Protobuf Java代码生成?

huangapple go评论65阅读模式
英文:

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类中,dateTimeFieldLocalDateTime 类型,其中包含已解析的日期时间。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月19日 21:43:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定