5

还有更具体的例子:

abstract trait A
trait B extends A
trait C extends A

如何检查扩展特征 A 的特征(可以从 0 到多个)在指定类中混合?

4

3 回答 3

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)
于 2010-05-11T15:34:19.780 回答
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)
于 2010-05-11T13:31:21.793 回答
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)

这仅查看由传入的实例的类直接实现的接口,但可以扩展为递归查找继承层次结构。

于 2010-05-11T14:53:51.370 回答