avro-tools将union类型转换为java.lang.Object

时间:2017-01-04 16:23:33

标签: java avro union-types avro-tools

.avpr Avro协议文件定义接收和返回联合类型的单个消息:

{
  "protocol": "Foo",
  "types": [
    {"name": "A", "type": "record",
     "fields": [{"name": "x", "type": "int"}]},
    {"name": "B", "type": "record",
     "fields": [{"name": "y", "type": "double"}]}
  ],
  "messages": {
    "bar": {
      "request": [{"name": "a_or_b", "type": ["A", "B"]}],
      "response": ["A", "B"]
    }
  }
}

让我们通过avro-tools

运行它
$ java -jar avro-tools-1.7.7.jar compile protocol test.avpr .

A.javaB.java并不奇怪。但Foo.java看起来像这样:

/**
 * Autogenerated by Avro
 * 
 * DO NOT EDIT DIRECTLY
 */

@SuppressWarnings("all")
@org.apache.avro.specific.AvroGenerated
public interface Foo {
  public static final org.apache.avro.Protocol PROTOCOL = org.apache.avro.Protocol.parse("{\"protocol\":\"Foo\",\"namespace\":null,\"types\":[{\"type\":\"record\",\"name\":\"A\",\"fields\":[{\"name\":\"x\",\"type\":\"int\"}]},{\"type\":\"record\",\"name\":\"B\",\"fields\":[{\"name\":\"y\",\"type\":\"double\"}]}],\"messages\":{\"bar\":{\"request\":[{\"name\":\"a_or_b\",\"type\":[\"A\",\"B\"]}],\"response\":[\"A\",\"B\"]}}}");
  java.lang.Object bar(java.lang.Object a_or_b) throws org.apache.avro.AvroRemoteException;

  @SuppressWarnings("all")
  public interface Callback extends Foo {
    public static final org.apache.avro.Protocol PROTOCOL = Foo.PROTOCOL;
    void bar(java.lang.Object a_or_b, org.apache.avro.ipc.Callback<java.lang.Object> callback) throws java.io.IOException;
  }
}

为什么我的A - 或 - B值变为java.lang.Object?我希望通用类型T<A, B>具有创建和检查我的union类型值的有用方法。

我应该如何处理我收到的Object参数,以区分AB类型,以及我应该返回什么样的价值?

谷歌搜索,我在GenericData中找到了一个名为resolveUnion的方法。它在这里有用吗?如果是这样,我该如何使用它?

0 个答案:

没有答案