Avro serialization with generic type issue

余生颓废 提交于 2019-12-11 07:58:01

问题


I need to write a function in Scala that returns an Array of byte serializated with AvroOutputStream, but in scala i can't get the class of the generic object i'm passing in input. Here is my util class:

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

As you can see if tou test this code is that AvroOutputStream can't recognize the T class so it can't generate a schema for it. Hope you can help! thanks

PS: Already tried with TypeTag and ClassTag, nothing works.


回答1:


You need to add the proper implicits for T, namely SchemaFor and ToRecord:

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


来源:https://stackoverflow.com/questions/48927440/avro-serialization-with-generic-type-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!