pree
pree

Reputation: 2357

java protocol buffers - populate sub message with the given field number and extension registry

I have been trying to construct/populate a sub-message/message using protobuf in java. To be more specific, I have the extension number for an extension along with the extension registry.

Is there a way to construct a message by populating the field with the given value?

In C++, I know there is a way to do this by using reflection. By using reflection interface, you can get the field descriptor (FindKnownExtensionByNumber()) and then construct the Message (MutableMessage(message, field descriptor)).

Is there a similar way to do it in Java?

Upvotes: 1

Views: 606

Answers (1)

Kenton Varda
Kenton Varda

Reputation: 45181

Starting with:

Message.Builder parent;
int extensionNumber;
ExtensionRegistry registry;

You can do:

// Look up the extension.
ExtensionRegsitry.ExtensionInfo info =
    registry.findExtensionByNumber(
        parent.getDescriptorForType(), extensionNumber);
if (info == null) {
  throw new IllegalArgumentException("no such extension");
}

// Make a new builder for a message of the extension's type.
Message.Builder builder =
    info.defaultInstance.newBuilderForType();

// ... fill in builder however you want ...

// Insert the new sub-message into the parent.
parent.setField(info.descriptor, builder.build());

Upvotes: 2

Related Questions