Reputation: 3033
Is there an introspection api somewhere in Scala to find the traits a class is implementing ?
For Scala 2.9.2 that is.
Upvotes: 2
Views: 158
Reputation: 899
Note that the example Kim Stebel used does not work if the trait is implemented by a superclass. Here is a more general form:
def implementsInterface(target: Class[_], someInterface: Class[_]): Boolean = {
val i = target.getInterfaces
i.foreach((c: Class[_]) => if (c == someInterface) return true)
val s = target.getSuperclass
if (s == null) false
else implementsInterface(s, someInterface)
}
Upvotes: 0
Reputation: 42047
Trait in Scala translate to interfaces in Java, so you can use Java's reflection library to find out which traits are implemented. Here is an example:
trait Foo
class Bar extends Foo
val b = new Bar
b.getClass.getInterfaces.foreach(println)
This prints:
interface Foo
interface scala.ScalaObject
Upvotes: 2