javaprotocol-buffersgrpcprotobuf-javaproto3

How to read a proto3 custom option from Java


Given the following service:

message Message {
  string content = 1;
}

service EchoService {
  rpc echo (Message) returns (Message) {
    option (google.api.http) = { get: "/echo" };
  }
}

I want to read the option from Java. My understand is the following code should work:

HttpRule rule = Message.getDescriptor()
  .getOptions()
  .getExtension(AnnotationsProto.http)

However this doesn't compile, complaining about typing issues where it cannot resolve the method.

I am trying to follow this: https://developers.google.com/protocol-buffers/docs/proto.html#customoptions

So the question is, how do I read the option from Java?


Solution

  • Well this is embarrassing, its actually a completely different type.

    AnnotationsProto.http implements type with a generic of MethodOptions (https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/DescriptorProtos.MethodOptions.html)

    Whereas Message.getDescriptor().getOptions().getExtensions() is expecting a parameter with a generic of MessageOptions (https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/DescriptorProtos.MessageOptions.html)

    MethodOptions vs MessageOptions - perhaps I need to get down to specsavers...