Protobuf java 从 DescriptorProto 创建描述符

ras*_*cio 2 java protocol-buffers proto

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)
Run Code Online (Sandbox Code Playgroud)

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

Raf*_*erm 5

问题是消息描述符通常依赖于其他消息,可能在其他文件中定义。因此,该库的顶级入口点是FileDescriptorFileDescriptorProto

在消息是独立的(只有原始字段)的情况下,应该很容易使用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());
}
Run Code Online (Sandbox Code Playgroud)