Apache Avro 可以在序列化期间处理参数化类型吗?
当我尝试序列化使用泛型的实例时,我看到 Avro 框架抛出此异常 -
org.apache.avro.AvroTypeException: Unknown type: T
at org.apache.avro.specific.SpecificData.createSchema(SpecificData.java:255)
at org.apache.avro.reflect.ReflectData.createSchema(ReflectData.java:514)
at org.apache.avro.reflect.ReflectData.createFieldSchema(ReflectData.java:593)
at org.apache.avro.reflect.ReflectData$AllowNull.createFieldSchema(ReflectData.java:75)
at org.apache.avro.reflect.ReflectData.createSchema(ReflectData.java:472)
at org.apache.avro.specific.SpecificData.getSchema(SpecificData.java:189)
我试图序列化的类看起来像这样
public class Property<T> {
private T propertyValue;
}
我正在尝试根据传入的 POJO 实例动态生成模式。我的序列化代码如下所示 -
ByteArrayOutputStream os = new ByteArrayOutputStream();
ReflectData reflectData = ReflectData.AllowNull.get();
Schema schema = reflectData.getSchema(propertyValue.getClass());
DatumWriter<T> writer = new ReflectDatumWriter<T>(schema);
Encoder encoder = EncoderFactory.get().jsonEncoder(schema, os);
writer.write(propertyValue, encoder);
我的代码中触发异常的行:
Schema schema = reflectData.getSchema(propertyValue.getClass());
对于没有参数化类型的类,相同的代码可以正常工作。
由于问题,自 1.7.7 版起,Avro 无法为参数化类型生成架构AVRO-1571 https://issues.apache.org/jira/browse/AVRO-1571。解决方法是显式指定参数化类型的架构,以便 Avro 不会尝试生成它:
private static final String PROPERTY_STRING_SCHEMA =
"{ " +
"\"type\": \"record\", " +
"\"name\": \"PropertyString\", " +
"\"fields\": [" +
"{ \"name\": \"propertyValue\", \"type\": \"string\" }" +
"] " +
"}";
@AvroSchema(PROPERTY_STRING_SCHEMA)
private Property<String> password;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)