在scala 2.10 AST中递归搜索元素的最佳方法是什么?
树可能是power.trees(code)或mirror.mkToolBox().parseExpr(code)
编辑的结果.在2.10.0-RC1 parseExpr中已重命名为parse.
我具体的用例是通过方法名称从给定的类/对象代码中提取方法的代码,但我认为如果以更通用的方式表达,问题将更加相关.
给定一个类型声明,我能够解析类型参数.
scala> reflect.runtime.universe.typeOf[List[Int]] match {case x:TypeRef => x.args}
res10: List[reflect.runtime.universe.Type] = List(Int)
Run Code Online (Sandbox Code Playgroud)
对于运行时值,相同的方法不起作用.
scala> reflect.runtime.currentMirror.reflect(List(42)).symbol.toType match {case x:TypeRef => x.args}
res11: List[reflect.runtime.universe.Type] = List(B)
Run Code Online (Sandbox Code Playgroud)
有没有办法克服反射值的类型擦除?
使用Java反射API,获取方法的参数类型列表,我们可以简单地使用getParameterTypes.
这是一个例子:
scala> classOf[String].getMethods.head.getParameterTypes
res8: Array[Class[_]] = Array(class java.lang.Object)
Run Code Online (Sandbox Code Playgroud)
使用新的Scala 2.10 Reflection API获得相同结果的最佳做法是什么?
给出一个反映的方法:
scala> val sortMethod = typeOf[::[_]].member(newTermName("sorted"))
sortMethod: reflect.runtime.universe.Symbol = method sorted
scala> sortMethod.typeSignature
res122: reflect.runtime.universe.Type = [B >: A](implicit ord: scala.math.Ordering[B])Repr
Run Code Online (Sandbox Code Playgroud)
找出方法是否具有隐式参数(在scala 2.10-M4 +中)的最佳方法是什么?