更具体的例子:
abstract trait A
trait B extends A
trait C extends A
如何检查延伸特征A(可以从0到多数)的特征是否在指定的类中混合?
答案 0 :(得分:3)
其他答案的混合怎么样
abstract trait A //interested in this one
trait B extends A //and this one
trait C extends A //this one too
trait D //don't care about this one though
val x = new A with B with D
x.getClass.getInterfaces.filter(classOf[A].isAssignableFrom(_))
返回
Array[java.lang.Class[_]] = Array(interface A, interface B)
答案 1 :(得分:1)
scala> val x = new A with B with C
x: java.lang.Object with A with B with C = $anon$1@8ea25fa
scala> x.getClass.getInterfaces
res11: Array[java.lang.Class[_]] = Array(interface A, interface B, interface C)
答案 2 :(得分:1)
这样的事情怎么样:
def getTraitsExtending(clazz:Class[_], baseTrait:Class[_]): Seq[Class[_]] = {
clazz.getInterfaces().filter { baseTrait isAssignableFrom _ }
}
这会找到clazz
实现的所有特征,这些特征本身就是baseTrait
的子特征。具有以下特征:
trait A
trait B extends A
trait C extends A
trait D
使用如下:
scala> val x1 = new C with B
x1: java.lang.Object with C with B = $anon$1@51d92803
scala> getTraitsExtending(x1.getClass, classOf[A])
res0: Seq[Class[_]] = WrappedArray(interface C, interface B)
scala> val x2 = new C with A
x2: java.lang.Object with C with A = $anon$1@f8db08
scala> getTraitsExtending(x2.getClass, classOf[A])
res1: Seq[Class[_]] = WrappedArray(interface C, interface A)
scala> val x3 = new C with D
x3: java.lang.Object with C with D = $anon$1@2bbd83d
scala> getTraitsExtending(x3.getClass, classOf[A])
res3: Seq[Class[_]] = WrappedArray(interface C)
这仅查看由传入的实例的类直接实现的接口,但可以扩展为递归查找继承层次结构。