Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've spent some time looking for some alternative to handle generic objects, I've seen questions similar to mine, but not as specific I suppose? Protocol buffers has multiple scalar types that I can use, however they are mostly primitive. I want my message to be flexible and be able to have a field that is a List of some sort.

Let's say my .proto file looked like this:

   message SomeMessage
   {
      string datetime = 1;
      message inputData // This would be a list
      {
         repeated Object object = 1;
      }
      message Object 
      {
          ? // this need to be of a generic type - This is my question
          // My work around - Using extentions with some Object
          //List all primitive scalar types as optional and create an extension 100 to    max;
      }
      message someObject //some random entity - for example, employee/company etc.
      {  
          optional string name = 1; optional int32 id = 2;
      }
      extend Object 
      {
          optional someObject obj = 101;
      }
  } 

And this would be fine, and would work, and I'd have a List where Objects could be of any primitive type or could be List < someObject >. However- The problem here, is that any time I needed to handle a new type of object, I'd need to edit my .proto file, recompile for C# and java (The languages I need it for)...

If protocol buffers is not able to handle generic object types, is there another alternative that can? Any help on this matter is greatly appreciated.

like image 240
shecodesthings Avatar asked Sep 06 '12 17:09

shecodesthings


People also ask

How do protocol buffers work?

Protocol buffers provide a language-neutral, platform-neutral, extensible mechanism for serializing structured data in a forward-compatible and backward-compatible way. It's like JSON, except it's smaller and faster, and it generates native language bindings.

What is protocol buffer in Grpc?

Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler.

What is .proto file in Java?

proto file. The definitions in a . proto file are simple: you add a message for each data structure you want to serialize, then specify a name and a type for each field in the message. Here is the . proto file that defines your messages, addressbook.


2 Answers

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

like image 99
shecodesthings Avatar answered Oct 11 '22 01:10

shecodesthings


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.

like image 11
Amareswar Avatar answered Oct 11 '22 01:10

Amareswar