Search code examples
scalakryo

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

Solution

  • 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]]