问题描述
看起来这让我很接近,但 (a) 不完全(见下文),并且 (b) 使用名称的字符串表示感觉就像一个黑客......
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 [...]
我是否遗漏了一些更直接的访问此信息的方法?或者它会是最好的,如果我在某个时候还需要类信息,只是为了保留一组并行的 Java 类信息?(呃!)
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!)
推荐答案
接收 java.lang.Class
或使用反射实例化对象必须使用镜像完成,而不是使用类型和符号,这是 Scala 的编译时间信息:
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
这篇关于从 Scala (2.10) 类型标记或符号获取 Java 类的任何方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!