How to use google.protobuf.Any

4,630 views
Skip to first unread message

Mikhail Melnik

unread,
Jun 2, 2015, 8:41:32 AM6/2/15
to prot...@googlegroups.com
Hi, everyone.

I have a vague idea of the purpose and common usage of the protobuf Any type.

Our team use java protobuf library.
We try to describe domain we're working on in protobuf terms and use Any as wrapper for unknown messages on compile time.

In some fields we keep Any as general type for any message so we do wrapping like this:

Any result = Any.newBuilder()
        .setTypeUrl(message.getClass().getClassName())
        .setValue(message.toByteString())
        .build();

to wrap our messages and later unwrap them and cast to certain message type.
We don't like fact that we use Java className as the type url, but didn't find better way yet.

We would like to put there protobuf message name:

message.getDescriptorForType().getFullName()

but we didn't find nice way to parse such Any object back to certain Message.

We also tried to find more documentation on Any type and understand what is the common usage of it.
Looks like there should be some utility methods to work with Any but they are not implemented yet.

Can anyone from google share their vision about usage of Any or point to documentation if we missed something there?
If anyone did use protobuf Any type and can make examples from own experience it would be also very useful.

Thanks in advance!

Feng Xiao

unread,
Jun 2, 2015, 2:09:32 PM6/2/15
to Mikhail Melnik, Protocol Buffers
In Java, the Any message will have several additional methods to do packing/unpacking. The method signature proposed looks like this:

class Any extends GeneratedMessage {
  static <T extends Message> Any pack(T value);

  // Throws exceptions if parsing fails or the type url doesn't match.
  <T extends Message> T unpack(Class<T> clazz);

  <T extends Message> boolean is(Class<T> clazz);
}

With these, your code could be simplified to:

Any result = Any.pack(message);

The default type url will be used (i.e., type.googleapis.com/full.message.name) in these methods.
 

Thanks in advance!

--
You received this message because you are subscribed to the Google Groups "Protocol Buffers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to protobuf+u...@googlegroups.com.
To post to this group, send email to prot...@googlegroups.com.
Visit this group at http://groups.google.com/group/protobuf.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages