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
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:
enum Type {
FOO = 0;
BAR = 1;
}
message Foo {
required Type type = 1;
}
message Bar {
required Type type = 1;
required string text = 2;
}
Basically message Bar extends message Foo (from practical side of course). Implementation in Java is simple too:
Bar bar = Bar.newBuilder().setType(Type.BAR).setText("example").build();
byte[] data = bar.toByteArray();
----
Foo foo = Foo.parseFrom(data);
if(foo.getType() == Type.BAR){
Bar bar = Bar.parseFrom(data);
System.out.println(bar.getText());
}
I known, it's not an elegant solution, but it's simple and logical.