来自 .proto 模式文件或字符串的原型描述符

Mik*_*ras 6 java protocol-buffers proto

我想从定义消息协议的字符串中获取原型描述符。例如我有:

public final static String schema = ""
    + "message Person {\n"
    + "   required string id = 1;\n"
    + "   required string name = 2;\n"
    + "}";

@Test
public void dynamicProto() throws IOException {
    DescriptorProtos.DescriptorProto descriptor = DescriptorProtos.DescriptorProto.parseFrom(schema.getBytes());

    boolean test = true;
    //do stuff
}
Run Code Online (Sandbox Code Playgroud)

我收到以下异常: com.google.protobuf.InvalidProtocolBufferException:协议消息标记的线路类型无效。

最终,我希望能够定义一个模式并在运行时接受实际的原始消息,而不是在编译时接受某些模拟服务类型的内容。

Mih*_*par 3

尝试创建字符串的描述符格式文件schema。如果您的消息在文件中描述,schema.proto您可以执行:

protoc --descriptor_set_out=desc.pb schema.proto

稍后,您应该使用以下命令在 java 中加载此文件:

InputStream input = new FileInputStream("desc.pb");
DescriptorProtos.DescriptorProto desc = DescriptorProtos.DescriptorProto.parseFrom(input);
Run Code Online (Sandbox Code Playgroud)