Finding method arguments (and types) using reflection Scala 2.10?

I learned (from here ) to use extractors to get Scala metadata. I also noticed Universe.MethodTypeExtractor :

MethodType(params, respte) class for creating and matching templates with MethodType(params, respte) syntax MethodType(params, respte) Here the parameters are a potentially empty list Parametric symbols of the method, and restpe is the result type of the Method.

Excellent! Looks like I want to! (?)

But how to get MethodType ? (And why is it an extractor for the "type" method ("types" methods?), Unlike, for example, the "Def" or "Ref" method ??)

 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) [...] 

Or am I completely barking the wrong tree, so to speak?

+6
source share
1 answer

paramss (this is the name RC1, in M7 it is called params ) and returnType are MethodSymbol methods:

 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 

To get a method type signature, you must call the typeSignature method defined in Symbol .

Speaking about why methods are types, it is not quite right to say. There are trees DefDef , MethodSymbol and MethodType / NullaryMethodType types, each of which performs its own tasks in the compiler. Pretty soon, we will complete the reflection API documentation, so I hope everything becomes clearer.

+4
source

Source: https://habr.com/ru/post/927521/


All Articles