简体   繁体   中英

Scala: classOf a generic

I want to load & parse a JSON file with scala 2.11.8, in a generic way, like this:

private val objectMapper = new ObjectMapper with ScalaObjectMapper
objectMapper.registerModule(DefaultScalaModule)

def loadFile[T](path: Path): Try[T] = Try(
  objectMapper.readValue(Files.readAllBytes(path), classOf[T])
)

Then the goal is to call the loadFile method with only the expected return type.

However this returns me:

class type required but T found

By googling, I found references to erasures, manifests, ClassTag but nothing works. What is the correct solution?

The generic type gets erased, so you need a ClassTag to make it work. This is how you can use them:

def loadFile[T: ClassTag](path: Path): Try[T] = Try(
  objectMapper.readValue(
    Files.readAllBytes(path),
    implicitly[ClassTag[T]].runtimeClass.asInstanceOf[Class[T]])
)

(For some reason, runtimeClass doesn't have the generic type, so you need the cast.)

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