2010-05-11 31 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

相關問題