问题描述
我正在查看 scala反射概述,想知道是否可以在Scala 2.10中将java.lang.Class<T>
用作类型.
I was looking at the scala reflection overview and I'm wondering if it is possible to use a java.lang.Class<T>
as a Type in Scala 2.10.
import scala.reflect.runtime.{ universe => ru }
class Reflector {
def getType: ru.Type = {
ru.typeOf[java.lang.String]
}
def getType[T](clazz: Class[T]): ru.Type = {
//is it possible to implement me?
}
}
是否可以在不更改其签名的情况下实现parse[T](clazz: Class[T]): ru.Type
方法,以便能够使用new Reflector().parse(String.class)
从Java调用它?
Is it possible to implement the parse[T](clazz: Class[T]): ru.Type
method without changing its signature in order to be able to call it from java with new Reflector().parse(String.class)
?
推荐答案
您可以像这样实现您的方法:
You could implement your method like this:
def getType[T](clazz: Class[T])(implicit runtimeMirror: ru.Mirror) =
runtimeMirror.classSymbol(clazz).toType
然后这样称呼它:
implicit val mirror = ru.runtimeMirror(getClass.getClassLoader)
getType(classOf[String])
您可能会对镜像库感兴趣,因为它包含类似的方法
You might be interested in the smirror library as it contains a similar method
def sClassOf[T](clazz: Class[T])(implicit runtimeMirror: Mirror): SClass[T]
SClass
包含typ
属性的地方.
您可能希望将方法更改为此(将保留相同的签名)
You might want to change the method to this (that would keep the same signature)
def getType[T](clazz: Class[T]):ru.Type = {
val runtimeMirror = ru.runtimeMirror(clazz.getClassLoader)
runtimeMirror.classSymbol(clazz).toType
}
这篇关于在Scala 2.10中获取java.lang.Class [T]的Scala类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!