假设我得到一个代表 List[Int] 的类型:
> import scala.reflect.runtime.universe
> val mirror = universe.runtimeMirror(this.getClass.getClassLoader)
mirror: reflect.runtime.universe.Mirror = JavaMirror with ...
> class X{ def getList():List[Int] = null }
defined class X
> val method = mirror.
classSymbol(classOf[X]).
toType.
declarations.
filter{_.isMethod}.
map{_.asInstanceOf[universe.MethodSymbol]}.
filter{ m => m.
name.
toString()=="getList" }.
head
method: reflect.runtime.universe.MethodSymbol = method getList
> val rt = method.returnType
rt: reflect.runtime.universe.Type = scala.List[scala.Int]
如何从reflect.runtime.universe.Type(显然知道类型参数scala.Int)到实际类型参数?
我看到 TypeSymbol 有一个参数
一些实验..
rt.typeSymbol // reflect.runtime.universe.Symbol = class List ... Int is erased
rt.typeSymbol.asInstanceOf[TypeSymbol].typeParams // List[reflect.runtime.universe.Symbol] = List(type A)
rt.takesTypeArgs // false !!
rt.termSymbol //None
rt.typeSymbol.typeSignature // Much, talk about generics, but no Int
rt.typeSymbol.asInstanceOf[TypeSymbol].typeParams // List[reflect.runtime.universe.Symbol] = List(type A)
rt.getClass // Class[_ <: reflect.runtime.universe.Type] = class scala.reflect.internal.Types$TypeRef$$anon$1
rt.asInstanceOf[TypeRef].sym // List
最佳答案
斯卡拉2.11
您需要rt.typeArgs
,它返回类型列表(在您的情况下,它包含单个元素:Int)。
斯卡拉2.10
val args = returnType match {
case r: universe.TypeRefApi => r.args
case _ => List()
}
关于scala - 如何在scala中获取reflect.runtime.universe.Type的类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852247/