使用协议缓冲区进行多态性的正确方法是什么? [英] what's the right way to do polymorphism with protocol buffers?

查看:69
本文介绍了使用协议缓冲区进行多态性的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Java 中长期序列化一组与强类层次结构相关的对象,并且由于它们的简单性、性能和易于升级,我想使用协议缓冲区来完成它.然而,它们并没有为多态性提供太多支持.现在,我处理它的方式是通过一个一条消息来统治所有"解决方案,该解决方案有一个必需的字符串 uri 字段,允许我通过反射实例化正确的类型,然后是一堆可选字段我可以序列化的其他可能的类,只使用其中一个(基于 uri 字段的值).有没有更好的方法来处理多态性,或者这和我要得到的一样好?

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?

推荐答案

proto3 中,extend 关键字已被替换.来自 docs:如果您已经熟悉 proto2 语法, Any 类型替换扩展名.

In proto3 the extend keyword has been replaced. From the docs: If you are already familiar with proto2 syntax, the Any type replaces extensions.

syntax = "proto3";

import "google/protobuf/any.proto";

message Foo {
  google.protobuf.Any bar = 1;
}

但要注意:Any 本质上是一个字节 blob.大多数时候最好使用 Oneof:

But beware: Any is essentially a bytes blob. Most of the times it is better to use Oneof:

syntax = "proto3";

message A {
    string a = 1;
}

message B {
    string b = 1;
}

message Foo {
  oneof bar {
    A a = 1;
    B b = 2;
  }
}

这篇关于使用协议缓冲区进行多态性的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆