Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java print protobuf object of unknown type

Consider that I have byte array - byte[] which represent some kind of serialized protobuf object. Is there any way to print it to output, something like

1: 123
2: Jhon
3: Doe
4: 0

Where 1 is int field, 2 and 3 are strings and 4 is boolen

TextFormat.print requires me to provide concrete Builder of protobuf object, which I do not know.

like image 370
user12384512 Avatar asked Mar 14 '16 13:03

user12384512


Video Answer


2 Answers

Define a type EmptyMessage like:

message EmptyMessage {
  // nothing
}

Now parse your message as EmptyMessage, then call toString() on it.

Why does this work? Well, consider that it is backwards-compatible to add fields to a message type. When you add a field, then send a message using that field to an old program that wasn't build with knowledge of the field, then the field is treated as as "unknown field". Unknown fields are printed as number / value pairs. Now, if you start with EmptyMessage and add fields, you can obviously get any other message. Therefore, all message types are "backwards-compatible" with EmptyMessage. Therefore, any message can be parsed as EmptyMessage to treat all the fields as unknown fields.

like image 165
Kenton Varda Avatar answered Sep 28 '22 05:09

Kenton Varda


if we can make the assumption that the fields are all primitive types (i.e. not sub-messages) then you should be able to loop through all the fields very simply -

for(Entry<FieldDescriptor, Object> entry : msg.getAllFields().entrySet())
{
    if(entry.getValue() != null)
        System.out.println(entry.getKey().getName() + ": " + entry.getValue().toString());
    else
    System.out.println(entry.getKey().toString() + ": null");
}

However, I am pretty sure that protobuf objects properly implement the toString() method, so I think you should be able to simply call

protoObj.toString()

to get a string representation of the protobuf object. For more info, take a look at: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/GeneratedMessage.ExtendableMessage#getAllFields%28%29

like image 38
William B. Avatar answered Sep 28 '22 06:09

William B.