具有通用类型问题的Avro序列化 [英] Avro serialization with generic type issue
问题描述
我需要在Scala中编写一个函数,该函数返回一个用AvroOutputStream序列化的字节数组,但是在Scala中,我无法获取输入中传递的通用对象的类. 这是我的util类:
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()
}
}
您可以看到您是否要测试此代码,因为AvroOutputStream无法识别T类,因此它无法为其生成模式. 希望能对您有所帮助!谢谢
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:已经尝试使用TypeTag和ClassTag,但没有任何效果.
PS: Already tried with TypeTag and ClassTag, nothing works.
推荐答案
您需要为T
添加适当的隐式,即SchemaFor
和ToRecord
:
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()
}
这篇关于具有通用类型问题的Avro序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!