【问题标题】:Can Apache Avro framework handle parameterized types during serialization?Apache Avro 框架可以在序列化期间处理参数化类型吗?
【发布时间】:2015-05-21 17:51:28
【问题描述】:

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

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

【问题讨论】:

    标签: java generics avro parameterized parameterized-types


    【解决方案1】:

    由于问题 AVRO-1571,Avro 1.7.7 版无法为参数化类型生成架构。一种解决方法是显式指定参数化类型的架构,这样 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; 
    

    【讨论】:

      猜你喜欢
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2011-06-01
      • 2018-03-23
      • 2021-11-15
      • 1970-01-01
      相关资源
      最近更新 更多