此.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.java
和B.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
参数,以区分A
和B
类型,以及我应该返回什么样的价值?
谷歌搜索,我在GenericData
中找到了一个名为resolveUnion
的方法。它在这里有用吗?如果是这样,我该如何使用它?