如何使用Scala/Kryo采用泛型类型的方法读取序列化对象?

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

当我知道特定的 class 类型时,使用 Kryo 读取序列化对象很容易,但是如果我想创建一个采用简单泛型类型的方法,该怎么做? 我有无法编译的代码:

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

我得到的错误是:

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

我知道错误的含义,但不知道正确的修复方法。

代码由我原来的特定类型代码修改:

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

我找到答案了,关键是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]])
}

在某些线程中,最后一行是:

kryo.readObject(input, tag.runtimeClass)

这对我来说不起作用,它必须是:

tag.runtimeClass.asInstanceOf[Class[M]]