Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

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

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!)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...