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?
标签:
protocol-buffers
相关问题
- creating callbacks and structs for repeated field
- How to deal with unknown protobuf fields in Java?
- Is it possible to use Apache Thrift without RPC?
- How do I Import a .proto file from a dependency ja
- compile protocol buffers 3 timestamp type in c# vi
相关文章
- How to not freeze the UI, and wait for response?
- Protocol message tag had invalid wire type
- Protobuf InvalidProtocolBufferException with some
- use protobuf3 with some lib which depends on proto
- How to serialize/deserialize a protobuf message th
- Parsing a raw Protocol Buffer byte stream in C#
- How can i write my own RPC Implementation for Prot
- Read value of enum extension in protocol buffer
Have you considered using extensions? You could have your uri field determine the type to use and then just load the appropriate extensions. If you know your fields are mutually exclusive then you could reuse the field id between separate extensions.
You have to handle this all yourself because protocol buffers aren't designed to be self describing beyond a simple list of values. This is touched on in the google techniques page.
In proto3 the
extend
keyword has been replaced. From the docs:If you are already familiar with proto2 syntax, the Any type replaces extensions.
But beware:
Any
is essentially a bytes blob. Most of the times it is better to useOneof
:Check out Extensions and Nested Extensions for a slightly cleaner way to do this.
This is not an anwer to the original question, but it may be helpful for others using v3 of Protocol Buffers. Version 3 disallows the
extensions
keyword. Runningprotoc
on the following file generates an error with the messageExtension ranges are not allowed in proto3
.There are a few techniques for implementing polymorphism. I try to cover them all here: Protocol Buffer Polymorphism
My preferred approach uses nested extensions:
Jon's solution is correct and working but pretty weird (for me). But Protocol Buffers is quite simple, so You can do something like that:
Basically message Bar extends message Foo (from practical side of course). Implementation in Java is simple too:
I known, it's not an elegant solution, but it's simple and logical.