我想要一个方法
def retrieve[T](value: Option[T])(implicit ct: ClassTag[T]): T;
在此方法中,我需要调用 Java 方法(超出我的控制范围)来创建
T
的实例。需要 Class[T]
:public <T> T construct(clazz: Class<T> /* other arguments */) { ... }
我怎样才能得到
Class[T]
来自 ClassTag[T]
?首先我想我可以使用 runtimeClass
来自 ClassTag
,但它的类型是 Class[_]
,不是 Class[T]
.或者有没有其他编译器可以自动提供的隐式值,我可以从中获取Class[T]
?
最佳答案
Here is the ticket在 getClass
和 linked forum discussion其中奥德斯基推测:
You could also use a cast.
Here is the duplicate ticket哪里
getClass
是固定的。 5.getClass
也投:/** Return the class object representing an unboxed value type,
* e.g. classOf[int], not classOf[java.lang.Integer]. The compiler
* rewrites expressions like 5.getClass to come here.
*/
def anyValClass[T <: AnyVal : ClassTag](value: T): jClass[T] =
classTag[T].runtimeClass.asInstanceOf[jClass[T]]
该限制让人想起 this question about pattern matching与
ClassTag
,其中也没有满足我们天真的期望。是否对
Class[A]
的阻力代表 Scala 类型和平台之间的阻抗不匹配?鉴于类(class)类型,真正能做的就是
newInstance
.但是使用构造函数镜像进行反射调用不会返回我的类型。scala> res24 reflectConstructor res25.asMethod
res27: reflect.runtime.universe.MethodMirror = constructor mirror for Bar.<init>(): Bar (bound to null)
scala> res27()
res28: Any = Bar@2eeb08d9
scala> bar.getClass.newInstance
res29: Bar = Bar@31512f0a
scala> classOf[Bar].newInstance
res30: Bar = Bar@2bc1d89f
这似乎不公平。
正如 2008 年的邮件主题所总结的那样,您希望在 Scala 中使用更少的强制转换。
顺便说一句,并不是我不相信代码注释,而是:
scala> 5.getClass
res38: Class[Int] = int
scala> :javap -
Size 1285 bytes
MD5 checksum a30a28543087238b563fb1983d7d139b
Compiled from "<console>"
[剪辑]
9: getstatic #27 // Field scala/runtime/ScalaRunTime$.MODULE$:Lscala/runtime/ScalaRunTime$;
12: iconst_5
13: invokestatic #33 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
16: getstatic #38 // Field scala/reflect/ClassTag$.MODULE$:Lscala/reflect/ClassTag$;
19: invokevirtual #42 // Method scala/reflect/ClassTag$.Int:()Lscala/reflect/ClassTag;
22: invokevirtual #46 // Method scala/runtime/ScalaRunTime$.anyValClass:(Ljava/lang/Object;Lscala/reflect/ClassTag;)Ljava/lang/Class;
25: putfield #18 // Field res38:Ljava/lang/Class;
28: return
关于class - 如何从隐式 ClassTag[T] 获取 Class[T]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18041078/