How do we construct a sub message by adding the extension field in protocol buffers. In C++, one way of doing it is by using MutableMessage(Message, FieldDescriptor) with reflection interface. How do we do the similar thing in Java?
I'm a newbie so don't know a lot about protocol buffers.
Following from jonathons answer, here is and example of creating and accessing extensions in java
Protobuf definition:
message Message
{
extensions 100 to max;
required uint64 A = 1;
}
message Event
{
extend Message {
required Event ext = 101;
optional string name = 102;
}
extensions 100 to max;
required uint64 B = 1;
}
Using the extension:
Extension01.Message.Builder bm = Extension01.Message.newBuilder();
Extension01.Message.Builder bm1 = Extension01.Message.newBuilder();
Extension01.Event.Builder be = Extension01.Event.newBuilder();
FileOutputStream out = new FileOutputStream(extFileOut);
be.setB(5678);
bm.setA(123);
bm.setExtension(Extension01.Event.ext, be.build()); // set the extension value
bm.build().writeDelimitedTo(out);
out.close();
FileInputStream in = new FileInputStream(extFileOut);
ExtensionRegistry registry = ExtensionRegistry.newInstance(); // create extension registry
Extension01.registerAllExtensions(registry); // Allocate the extensions
bm1.mergeDelimitedFrom(in, registry);
in.close();
Event extension = bm1.getExtension(Extension01.Event.ext); // get the extension
if (extension == null) {
System.out.println("No extension");
} else {
System.out.println(extension.getB());
}
Edit:
Line setting extension value:
bm.setExtension(Extension01.Event.ext, be.build());
The variable Extension01.Event.ext is generated by protocol buffers and can be used get/put the values of extensions.
Edit 2:
This is how I think extensionInfo is used (I have not tried it my self):
ExtensionInfo extensionInfo = registry.findExtensionByNumber(..., 101);
bm1.getField(extensionInfo.descriptor);
bm1.setField(extensionInfo.descriptor, value)
Use the setExtension method. Given:
message Bar {
extend Foo {
optional string foo_string = 1;
}
}
You can build a Bar message as so:
Foo foo = Foo.newBuilder()
.setExtension(Bar.fooString, "My foo string")
.build();
See the Java Generated Code documentation on extensions for Protocol Buffers for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With