简体   繁体   English

内省Scala类的特征?

[英]Introspect a Scala class for traits?

Is there an introspection api somewhere in Scala to find the traits a class is implementing ? Scala中是否有自省api来查找类正在实现的特征?

For Scala 2.9.2 that is. 对于Scala 2.9.2。

Trait in Scala translate to interfaces in Java, so you can use Java's reflection library to find out which traits are implemented. Scala中的特性转换为Java中的接口,因此您可以使用Java的反射库来找出实现了哪些特征。 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. 请注意,如果特征由超类实现,则Kim Stebel使用的示例不起作用。 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)
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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