Prasath
Prasath

Reputation: 1284

Create new builder using com.google.protobuf.Descriptors.Descriptor

I need to create newBuilder() of a class for a given com.google.protobuf.Descriptors.Descriptor.

I have created a jar using google proto buffer for the following protocol :

message Foo
{
  optional uint32 id = 1;
  optional string fooName = 2;
}
message Bar
{
  optional uint32 id = 1;
  optional string barName = 2;
}

From Java side, based on Descriptor I need to create newBuilder(). For example :

    Message.Builder message;
    if(Descriptor.getName().equals("Foo"))
        message = Foo.newBuilder();
    if(Descriptor.getName().equals("Bar"))
        message = Bar.newBuilder();

But I don't want to go for if else or switch case. Also I have tried some other way using DynamicMessage.

Message.Builder message = DynamicMessage.newBuilder(descriptor);

But in this case I am not able to cast it into Foo or Bar class. Is there any other way to create newBuilder() using Descriptor or Descriptor name?

Blindly I need newBuilder() of given class name like this :

Message.Builder message = SomeUtilClass.getNewBuilder("Foo");

Upvotes: 3

Views: 6369

Answers (1)

Andy Turner
Andy Turner

Reputation: 140299

You can't create a Builder from a Descriptor. A Descriptor has no type information as to the proto (or builder) class that it need to create, because all Descriptor instances are of the same class (it's final).

If you can only work with the Descriptor, your if/else is roughly as good as you can get. (I say roughly because you could do it with a map or a switch instead; but it's basically the same).

A better approach would be to work with the default instance of the proto that you are trying to create (or any other instance of that proto; but the default instance is simplest to obtain).

Message prototype = Foo.getDefaultInstance();  // Or Bar.getDefaultInstance().

because from Message you can get both a builder and the descriptor:

Message.Builder builder = prototype.newBuilderForType();
Descriptor descriptor = prototype.getDescriptorForType();

Upvotes: 5

Related Questions