如何在scala中键入reflect.runtime.universe.Type的参数? [英] How to get to type parameters of a reflect.runtime.universe.Type in scala?

查看:276
本文介绍了如何在scala中键入reflect.runtime.universe.Type的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我得到一个表示List [Int]的类型:

Suppose I get a Type representing 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)变成实际的类型参数?

How to I go from reflect.runtime.universe.Type (that apparently knows about the type parameter scala.Int) to the actual type parameters?

我看到TypeSymbol有一个参数

I see that TypeSymbol has a parm

一些实验.

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

推荐答案

Scala 2.11

您需要rt.typeArgs,它返回类型列表(在您的情况下,它包含一个元素:Int).

Scala 2.11

You need rt.typeArgs, which returns a list of types (in your case it contains a single element: Int).

val args = returnType match {
  case r: universe.TypeRefApi => r.args
  case _ => List()
}

这篇关于如何在scala中键入reflect.runtime.universe.Type的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆