Any way to obtain a Java class from a Scala (2.10) type tag or symbol?

*爱你&永不变心* 提交于 2019-11-28 09:03:24

Receiving a java.lang.Class or instantiating objects with reflection must be done with a mirror and not with types and symbols, which are compile time information for Scala:

scala> val m = runtimeMirror(getClass.getClassLoader)
m: reflect.runtime.universe.Mirror = JavaMirror with ...

scala> m.runtimeClass(typeOf[X.Y].typeSymbol.asClass)
res25: Class[_] = class X$Y

Assuming tag is the type tag of the class you want to get the java class for, you can say:

val mirror = tag.mirror
val clazz = mirror.runtimeClass(tag.tpe.typeSymbol.asClass)

Basically the same as sschaef's answer, except you should use the mirror directly from the tag, instead of using the mirror of the current class' classloader. If the current class and the other class which you have the tag for use diferent classloaders, you would have a classloading error in that case, but no error in the way I explained.

The clazz variable will hold the java class for whatever you're trying to get.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!