简体   繁体   中英

How to read serialized object with a method taking generic type by Scala/Kryo?

Use Kryo to read serialized object is easy when I know the specific class type, but if I want to create a method that takes simple generic type, how to do it? I have code that can not be compiled:

def load[T](path: String): T = {
    val instantiator = new ScalaKryoInstantiator
    instantiator.setRegistrationRequired(false)
    val kryo = instantiator.newKryo()
    val input = new Input(FileUtils.readFileToByteArray(new File(path)))
    kryo.readObject[T](input, classOf[T])
}

The error I got is:

class type required but T found
    kryo.readObject[T](input, classOf[T])

I know what the error means, but don't know the right way to fix it.

The code is modified by my original type-specific code:

def load(path: String): SomeClassType = {
    val instantiator = new ScalaKryoInstantiator
    instantiator.setRegistrationRequired(false)
    val kryo = instantiator.newKryo()
    val input = new Input(FileUtils.readFileToByteArray(new File(path)))
    kryo.readObject(input, classOf[SomeClassType])
} 

I've found the answer, the key is ClassTag :

def load[M: ClassTag](path: String)(implicit tag: ClassTag[M]): M = {
    val instantiator = new ScalaKryoInstantiator
    instantiator.setRegistrationRequired(false)
    val kryo = instantiator.newKryo()
    val input = new Input(FileUtils.readFileToByteArray(new File(path)))
    kryo.readObject(input, tag.runtimeClass.asInstanceOf[Class[M]])
}

In some threads, the last line is:

kryo.readObject(input, tag.runtimeClass)

This doesn't work in my case, it has to be:

tag.runtimeClass.asInstanceOf[Class[M]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM