Mike Samaras
Mike Samaras

Reputation: 406

Proto Descriptor from .proto schema file or String

I would like to get a proto Descriptor from a string that defines the message protocol. For example I have:

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
}

I get the following exception: com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.

Ultimately I want to be able to define a schema and accept the actual proto message at runtime as opposed to compile time for some mock service type stuff.

Upvotes: 8

Views: 4821

Answers (1)

stuparm
stuparm

Reputation: 553

Try to create a descriptor formatted file of your schema string. If your message is described in schema.proto file you can execute:

protoc --descriptor_set_out=desc.pb schema.proto

Later, you should load this file in java using:

InputStream input = new FileInputStream("desc.pb");
DescriptorProtos.DescriptorProto desc = DescriptorProtos.DescriptorProto.parseFrom(input);

Upvotes: 4

Related Questions