简体   繁体   中英

Introspect a Scala class for traits?

Is there an introspection api somewhere in Scala to find the traits a class is implementing ?

For Scala 2.9.2 that is.

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

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)
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM