scala reflection, cast type with asInstanceOf
I have
trait T
class C extends T
compiled to .class files. Run scala with -cp <...>
to have type T
available. Then load class C using reflection:
val loader = ScalaClassLoader fromURLs (/* List[URL] */)
val anyC = loader.tryToInitializeClass("C") getOrElse (/* throw something */)
val classC = anyC.asInstanceOf[Class[T]]
How can I cast a classC开发者_运维技巧.newInstance
into type T
like
val objC = classC.newInstance.asInstanceOf[T]
// yields java.lang.ClassCastException: C cannot be cast to T
You must be loading class C
from a different classloader than the one T
is being loaded from.
You've put both T
and C
on the REPLs classpath, so one option would be to load C
via the system classloader. Sample REPL session,
scala> val loader = scala.tools.nsc.util.ScalaClassLoader.getSystemLoader
loader: scala.tools.nsc.util.ScalaClassLoader =
scala.tools.nsc.util.ScalaClassLoader$$anon$1@985d2e0
scala> val anyC = loader.tryToInitializeClass("C") getOrElse (sys.error("Boom"))
anyC: Class[Nothing] = class C
scala> val classC = anyC.asInstanceOf[Class[T]]
classC: Class[T] = class C
Nb. this isn't really a Scala-specific question any longer.
精彩评论