Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting method parameter types using scala 2.10 reflection API

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?

like image 792
Sagie Davidovich Avatar asked Sep 21 '25 09:09

Sagie Davidovich


1 Answers

It's more difficult, because Scala reflection does more and need more. For example:

  • The types are not erased. The classes are erased, but not the types.
  • Scala supports named parameters, so you need the name of the parameters.
  • Scala has methods without parameter lists.

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
like image 110
Daniel C. Sobral Avatar answered Sep 22 '25 22:09

Daniel C. Sobral