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());
同样的代码对于没有参数化类型的类也能正常工作。
最佳答案
由于问题 AVRO-1571,自版本 1.7.7 起的 Avro 无法为参数化类型生成模式.解决方法是显式指定参数化类型的架构,这样 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;
关于java - Apache Avro 框架可以在序列化期间处理参数化类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666618/