2010-05-11 33 views

回答

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
scala> val x = new A with B with C 
x: java.lang.Object with A with B with C = [email protected] 

scala> x.getClass.getInterfaces 
res11: Array[java.lang.Class[_]] = Array(interface A, interface B, interface C) 
+0

我曾想过这种明显的方法,但决定在这里提出,因为特质,因为我知道在复杂的方式进行编译。 – Jeriho 2010-05-11 15:01:11

+0

当语言功能足够时,千万不要诉诸反思。 – 2010-05-11 15:11:57

+0

同意。我第一次使用isInstanceOf - 这回答了他的问题的主体。但是当我重新阅读他的实际问题标题“如何获得特征列表......”时,我转而使用getInterfaces。 – 2010-05-11 15:14:52

1

怎么是这样的:

def getTraitsExtending(clazz:Class[_], baseTrait:Class[_]): Seq[Class[_]] = { 
    clazz.getInterfaces().filter { baseTrait isAssignableFrom _ } 
} 

此找到所有特质,clazz实现了自身的baseTrait subtraits。具有以下特点:

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 = [email protected] 

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 = [email protected] 

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 = [email protected] 

scala> getTraitsExtending(x3.getClass, classOf[A]) 
res3: Seq[Class[_]] = WrappedArray(interface C) 

这仅着眼于那些直接由类传入的实例实现的接口,但可以扩展到递归看建立继承层次结构。

+0

这看起来很像我的回答+一些样板:) – 2010-05-12 15:41:08

+0

@Kevin - 日期戳记说你的答案看起来像一个可怕很多像我的答案... :-P – 2010-05-12 16:19:18

+0

这不是我看到,当我点“最新”:) – 2010-05-13 07:43:25

相关问题