【问题标题】:Protobuf java create a Descriptor from DescriptorProtoProtobuf java 从 DescriptorProto 创建一个描述符
【发布时间】:2021-08-05 13:05:19
【问题描述】:

我正在寻找一种从com.google.protobuf.DescriptorProtos.DescriptorProtocom.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)

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

【问题讨论】:

    标签: java protocol-buffers proto


    【解决方案1】:

    问题在于消息描述符通常依赖于可能在其他文件中定义的其他消息。所以库的顶级入口点是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());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-27
      相关资源
      最近更新 更多