Reputation: 9279
I was looking for a way to create from a com.google.protobuf.DescriptorProtos.DescriptorProto
a com.google.protobuf.Descriptors.Descriptor
Like doing:
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. I'm start to thinking that it is not possible, as this function would be the protobuf compiler itself, and it is built to output .java files, so cannot be called at runtime
Upvotes: 2
Views: 3402
Reputation: 1400
The issue is that message descriptors often depend on other messages, possibly defined in other files. So the top-level entry point for the library is FileDescriptor
and FileDescriptorProto
.
In the case where the message is self-contained (only primitive fields), it should be easy to just wrap the DescriptorProto
using something like:
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());
}
Upvotes: 5