Evan is correct. The best way to write code which deals with a generic
protobuf type is to have it take a default instance as a parameter. From
that you can do everything else.
This is actually better than passing around Class objects, because it allows
users to use DynamicMessages with your code. Using Class objects forces
users to use only generated types. Also, Java reflection may be slow or
even unavailable on some platforms.
On Mon, Dec 6, 2010 at 7:51 AM, Evan Jones <ev...@mit.edu> wrote:
> On Dec 6, 2010, at 10:31 , Koert Kuipers wrote:
>> But that doesn't make a parseFrom() in message interface invalid, does it?
>> Indeed some other information outside the raw bytes will be needed to pick
>> to right Message subclass. But that's fine.
> Oh, sorry, I misunderstood your question, so my answer is somewhat invalid.
> One could then:
>> 1) pick the right subclass of Message based upon some information outside
>> the raw bytes (in my case something stored in a protobuf wrapper around the
>> raw bytes)
>> 2) call subclass.parseFrom(bytes)
>> now we have to jump through more hoops for step 2 (create instance of
>> Message subclass, newBuilderForType, mergeFrom, isInitialized, build)
> The MessageLite.Builder interface has a mergeFrom method that does what you
> want. What you should do is something like:
> * Get a MessageLite instance for the message type you want to parse (eg.
> something like MyMessageType.getDefaultInstance(), or
> * Hold on to that MessageLite instance in some sort of registry.
> (HashMap<Integer, MessageLite>?)
> * When you get a message, look at the protobuf wrapper to determine the
> * Look up the "prototype" MessageLite instance in your registry.
> * Call prototypeInstance.newBuilderForType().mergeFrom(bytes).build()
> This only creates a single instance of the message each time. The .build()
> method will automatically check that the message is initialized, so you
> don't need to call isInitialized (although you may want to catch the
> exception it could throw?).
> This Builder pattern is used so that the Message objects are immutable.
> This means they can be passed between threads without requiring any
> synchronization. See:
> Hope this helps,
> Evan Jones
> You received this message because you are subscribed to the Google Groups
> "Protocol Buffers" group.
> To post to this group, send email to proto...@googlegroups.com.
> To unsubscribe from this group, send email to
> For more options, visit this group at
You received this message because you are subscribed to the Google Groups
"Protocol Buffers" group.
To post to this group, send email to proto...@googlegroups.com.
To unsubscribe from this group, send email to
For more options, visit this group at