3

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());

相同的代码适用于没有参数化类型的类。

4

1 回答 1

3

由于问题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; 
于 2015-05-21T09:29:06.627 回答