Tim*_*Tim 6 reflection scala scala-2.10
我已经(从这里)学习使用提取器来获取Scala元数据.我也注意到了Universe.MethodTypeExtractor:
用于创建和模式匹配语法的提取器类
MethodType(params, respte)此处,params是方法的参数符号的潜在空列表,而restpe是方法的结果类型.
大!听起来像我想要的!(?)
但是如何得到一个MethodType?(为什么这是方法"type"的提取器(方法"类型"?)而不是说方法"Def"或"Ref"??)
scala> typeOf[List[Int]].member(newTermName("head"))
res2: reflect.runtime.universe.Symbol = method head
scala> res2 match { case MethodType(a, b) => println((a, b)) }
scala.MatchError: method head (of class scala.reflect.internal.Symbols$MethodSymbol) [...]
scala> res2.asType match { case MethodType(a, b) => println((a, b)) }
scala.ScalaReflectionException: method head is not a type [...]
scala> res2.asTerm match { case MethodType(a, b) => println((a, b)) }
scala.MatchError: method head (of class scala.reflect.internal.Symbols$MethodSymbol) [...]
scala> res2.asMethod match { case MethodType(a, b) => println((a, b)) }
scala.MatchError: method head (of class scala.reflect.internal.Symbols$MethodSymbol) [...]
Run Code Online (Sandbox Code Playgroud)
或者我完全"吠叫错误的树",可以这么说吗?
paramss(这是一个 RC1 名称,在 M7 中它被命名为params)并且returnType是 MethodSymbol 的方法:
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> typeOf[List[Int]].member(newTermName("head"))
res2: reflect.runtime.universe.Symbol = method head
scala> res2.asMethod.paramss
res4: List[List[reflect.runtime.universe.Symbol]] = List()
scala> res2.asMethod.returnType
res5: reflect.runtime.universe.Type = A
Run Code Online (Sandbox Code Playgroud)
要获取方法的类型签名,您应该调用typeSignature上定义的方法Symbol。
说到为什么方法是类型,这样说并不完全正确。有DefDef树、MethodSymbol符号和MethodType/NullaryMethodType类型——每一个在编译器中都有自己的用途。很快我们就会完成反射 API 的文档,所以希望事情会变得更加清晰。