Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Looks like this gets me close, but (a) not quite (see below), and (b) using the string representation of a name feels like a hack...

scala> import scala.reflect.runtime.universe._import scala.reflect.runtime.universe._

scala> val t = typeOf[Int]
t: reflect.runtime.universe.Type = Int

scala> t.typeSymbol.asClass.fullName
res0: String = scala.Int

scala> object X { class Y } 
defined module X

scala> val y = typeOf[X.Y]
y: reflect.runtime.universe.Type = X.Y

scala> Class.forName(y.typeSymbol.asClass.fullName)
java.lang.ClassNotFoundException: X.Y [...]

Am I missing some more direct method of accessing this information? Or is it going to be best, if I also need the class information at some point, just to keep a parallel set of Java class info? (Ugh!)

like image 928
Tim Avatar asked Oct 15 '12 18:10

Tim


2 Answers

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
like image 191
kiritsuku Avatar answered Oct 15 '22 18:10

kiritsuku


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.

like image 40
Angel Blanco Avatar answered Oct 15 '22 16:10

Angel Blanco