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

后端 未结 6 2050
忘了有多久
忘了有多久 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 18:11

    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.

提交回复
热议问题