what's the right way to do polymorphism with p

2019-01-13 05:26发布

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, performance, and ease of upgrade. However, they don't provide much support for polymorphism. Right now, the way I'm handling it is by having a "one message to rule them all" solution that has a required string uri field that allows me to instantiate the correct type via reflection, then a bunch of optional fields for all the other possible classes I could serialize, only one of which will be used (based on the value of the uri field). Is there a better way to handle polymorphism, or is this as good as I'm going to get?

7条回答
地球回转人心会变
2楼-- · 2019-01-13 06:12

A solution a little better, for me, that the @Łukasz Marciniak's answer.

If Bar extends Foo, simply write:

message Bar {
   optional Foo foo = 1;
   optional double aDouble = 2;
}
message Foo {
   optional string aString = 1;
}

So if Foo evolves only Foo message is modified.

查看更多
登录 后发表回答