When I research a new library, I sometimes find it hard to locate the implementation of a method.
In Java, Metho#getDeclaringClass provides the class that declared a given method. So by iterating over Class#getMethods, I can find for each method, the class that declared it.
In Scala, traits are converted to Java interfaces and a class that extends a trait will implement the methods of the trait by forwarding them to a companion class defining these methods statically. This means, that Method#getDeclaringClass will return the class, not the trait:
scala> trait A { def foo = {println("hi")}}
defined trait A
scala> class B extends A
defined class B
scala> classOf[B].getMethods.find(_.getName() == "foo").get.getDeclaringClass
res3: java.lang.Class[_] = class B
What is the best way to work around this? Meaning, given a class, how can I get a List[(Method, Class)] where each tuple is a method and the trait/class it was declared in?
In Scala 2.8 you can use the ScalaSigParser to parse the scala specific byte code information.
This will be more stable than the byte code serialization format of scala traits, classes and methods.
Prints:
I suppose following this road you can build a reflection API for Scala.