Skip to content
Advertisement

Generic getDefaultInstance() for java protobuf

I’m trying to write a static util function that takes in a protobuf object and determine if it’s a default instance, something along the line of:

static boolean isDefault(ProtobufMessage m) {
  return m.equals(m.getDefaultInstance())
}

Would like for it to be able to apply to a range of protobuf objects like Struct / Types / Messages, however getDefaultInstance() appears to only get defined in the child classes.

I’m thinking along the lines of polymorphism or generics but unsure if it can be applied in this case, does anyone have any idea?

Advertisement

Answer

Bit late to this question, but you could make use of getDefaultInstanceForType(), which comes from the MessageLiteOrBuilder class and isn’t static:

import com.google.protobuf.Message;
import java.util.Objects;

static boolean isDefault(Message m) {
  return Objects.equals(m.getDefaultInstanceForType(), m);
}

Here is the method in the docs: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLiteOrBuilder.html#getDefaultInstanceForType–

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement