4

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?

1 Answer 1

12

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
Sign up to request clarification or add additional context in comments.

1 Comment

Daniel, Thanks for your answer. it worked well, but I am surprised that scala reflection API doesn't encapsulate this functionality, which seems to be basic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.