dimanche 26 avril 2020

Protobuf Java Reflection

I'm trying to deserialize protobuf messages via reflection. Specifically I'm trying to send events over a queue but that does not really affect the problem. Here is the situation:

  • Service A has .proto file with definitions. Using a maven plugin I generated the code for this messages. When a message instance is serialized I write over the wire the length of the byte[], the descriptor full name and the data itself. This works flawlessly.
  • Service B has the same version of the .proto file and has the same classes autogenerated. When I receive the message I lookup for the type Descriptor using the protobuf FileDescriptor. Here is my problem, I cannot really build an instance of type T using its descriptor. Not even a instance of Object which could be later downcasted.

I could use DynamicMessage.parseFrom but that's not a real solution as I could not downcast later. I've been researching and looks like the way to go is using Message.getDefaultInstance and later call newBuilderForType.mergeFrom(byte []). But there is no way to programatically access to all the default instances given a FileDescriptor so any user should list all the messages available on a given descriptor and invoke the defaultInstance method. Other option is to send the full package name over the wire and rely on Class.forName to locate the class and the invoke getDefaultInstance but this is not very safe.

My question is: Is there an easier way of building generic instances of protobuf classes or I have missed something?

Note: The signature of the event handler would look like public void onT( T event ); that's why the downcast is important rather than relying on DynamicMessage





Aucun commentaire:

Enregistrer un commentaire