Protobuf java 从 DescriptorProto 创建一个 Descriptor

Protobuf java create a Descriptor from DescriptorProto

我正在寻找一种从 com.google.protobuf.DescriptorProtos.DescriptorProto 创建 com.google.protobuf.Descriptors.Descriptor

的方法

喜欢做:

var descProto = DescriptorProtos.DescriptorProto.newBuilder()
            .setName("MyDynamicType")
            .addField(DescriptorProtos.FieldDescriptorProto.newBuilder()
                .setName("my_dynamic_field")
                .setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING)
            )
            .build()
Descriptors.Descriptor descriptor = theResponseToThisQuestion(descProto)

P.S。我开始认为这是不可能的,因为这个函数本身就是 protobuf 编译器,它是为输出 .java 文件而构建的,所以不能在运行时调用

问题是消息描述符通常依赖于其他消息,可能在其他文件中定义。所以库的顶级入口点是 FileDescriptor and FileDescriptorProto.

在消息是自包含的(只有原始字段)的情况下,使用类似的东西包装 DescriptorProto 应该很容易:

Descriptor standaloneMessage(DescriptorProto message) 
    throws DescriptorValidationException {
  FileDescriptorProto file = FileDescriptorProto.newBuilder()
      .setName("synthetic_file.proto")
      .addMessageType(message)
      .build();
  FileDescriptor file = FileDescriptor.buildFrom(file, new FileDescriptorProto[]{});
  return file.findMessageTypeByName(message.getName());
}