假设我得到一个表示 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