How to handle the generic type Object with protocol buffers, in the .proto file?

As Marc Gravell stated above - Protocol Buffers do not handle generics or inheritance.


Though I am late, just for the sake of new audience, you can use bytes in place of object and that can be any object which you can serialize/de-serialize.


It IS possible to achieve generic message functionality but still adding new types will require rebuilding proto classes.

You use wrapper class

message Wrapper {
    extensions 1000 to max;
    required uint32 type = 1;
}

Then add some types

message Foo {
    extend Wrapper {
        optional Foo item = 1000;
    }

    optional int attr1_of_foo = 1;
    optional int attr2_of_foo = 2;
    optional int attr3_of_foo = 3;
}

message Bar {
    extend Wrapper {
        optional Bar item = 1001;
    }

    optional int attr1_of_bar = 1;
    optional int attr2_of_bar = 2;
    optional int attr3_of_bar = 3;
}

See how we extending Wrapper class in classes that we want to be stored by Wrapper class using extension.

Now, example of creating Foo wrapped object. I'm using Python, since it's most condensed form. Other languages can do the same.

wrapper = Wrapper()
wrapper.type = Foo.ITEM_FIELD_NUMBER
foo = wrapper.Extensions[Foo.item]
foo.attr1_of_foo = 1
foo.attr2_of_foo = 2
foo.attr3_of_foo = 3
data = wrapper.SerializeToString()

And example of deserializing

wrapper = Wrapper()
wrapper.ParseFromString(data)
if wrapper.type == Foo.ITEM_FIELD_NUMBER:
    foo = wrapper.Extensions[Foo.item]
elif wrapper.type == Bar.ITEM_FIELD_NUMBER:
    bar = wrapper.Extensions[Bar.item]
else:
    raise Exception('Unrecognized wrapped type: %s' % wrapper.type)

Now, because you want generic collection, make Wrapper a repeated field of other message and voilà.

Of course it's not complete solution, this architecture will need some more packaging to make it easy to use. For more information read about Protobuf extensions, especially nested ones (https://developers.google.com/protocol-buffers/docs/proto#nested) or google about item marshalling.