what's the right way to do polymorphism with protocol buffers?

后端 未结 6 2057
忘了有多久
忘了有多久 2020-12-04 17:50

I\'m trying to long-term serialize a bunch of objects related by a strong class hierarchy in java, and I\'d like to use protocol buffers to do it due to their simplicity, pe

6条回答
  •  难免孤独
    2020-12-04 17:58

    There are a few techniques for implementing polymorphism. I try to cover them all here: Protocol Buffer Polymorphism

    My preferred approach uses nested extensions:

    message Animal
    {
        extensions 100 to max;
    
        enum Type
        {
            Cat = 1;
            Dog = 2;
        }
    
        required Type type = 1;
    }
    
    message Cat
    {
        extend Animal
        {
            required Cat animal = 100; // Unique Animal extension number
        }
    
        // These fields can use the full number range.
        optional bool declawed = 1;
    }
    
    message Dog
    {
        extend Animal
        {
            required Dog animal = 101; // Unique Animal extension number
        }
    
        // These fields can use the full number range.
        optional uint32 bones_buried = 1;
    }
    

提交回复
热议问题