【问题标题】:Avro serialization with generic type issue具有泛型类型问题的 Avro 序列化
【发布时间】:2018-07-28 14:57:14
【问题描述】:

我需要在 Scala 中编写一个函数,该函数返回一个使用 AvroOutputStream 序列化的字节数组,但在 scala 中我无法获取我在输入中传递的通用对象的类。 这是我的实用程序类:

class AvroUtils {

    def createByteArray[T](obj: T): Array[Byte] = {
        val byteArrayStream = new ByteArrayOutputStream()
        val output = AvroOutputStream.binary[T](byteArrayStream)
        output.write(obj)
        output.close()
        byteArrayStream.toByteArray()
    }
}

如您所见,如果您测试此代码是 AvroOutputStream 无法识别 T 类,因此它无法为其生成模式。 希望你能帮忙!谢谢

PS:已经尝试过使用 TypeTag 和 ClassTag,没有任何效果。

【问题讨论】:

    标签: scala generics avro avro4s


    【解决方案1】:

    您需要为T 添加适当的隐式,即SchemaForToRecord

    def createByteArray[T : SchemaFor : ToRecord](obj: T): Array[Byte] = {
      val byteArrayStream = new ByteArrayOutputStream()
      val output = AvroOutputStream.binary[T](byteArrayStream)
      output.write(obj)
      output.close()
      byteArrayStream.toByteArray()
    }
    

    【讨论】:

    • 也许 ... def createByteArray[T : SchemaFor : ToRecord](obj: T): Array[Byte] ?
    • 如果其中一个字段是 AnyRef AvroInputStream.binary[T](byteArrayStream) 编译失败,我还有另一个问题:找不到隐式 SchemaFor
    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多