Using the Java reflection API, to get the list of parameter types for a method we can simply use getParameterTypes
.
Here's an example:
scala> classOf[String].getMethods.head.getParameterTypes
res8: Array[Class[_]] = Array(class java.lang.Object)
What's the best practice to get the same result using the the new Scala 2.10 Reflection API?
It's more difficult, because Scala reflection does more and need more. For example:
So, given all that, here's how you do it. First, get the methods:
val stringMethods: Iterable[MethodSymbol] = typeOf[String].members.collect {
case m if m.isMethod => m.asMethod
}
Scala reflection doesn't (yet) provide methods to list specific kinds of members (methods, fields, inner classes, etc), so you need to use the general members
method.
Working for all kinds of members, the members
method returns an iterable of Symbol
, the greatest common denominator of all symbols, so you'll need to cast to MethodSymbol
to treat the resulting symbols as methods.
Now, let's say we have a MethodSymbol
, and we want the types of arguments. We can do this:
method.paramLists
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With