问题
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