和更具體的例子:如何獲得在指定類中混合的特徵列表?
abstract trait A
trait B extends A
trait C extends A
如何檢查在指定的類漲跌互現什麼擴展性狀A(也可以是從0到許多)特質?
和更具體的例子:如何獲得在指定類中混合的特徵列表?
abstract trait A
trait B extends A
trait C extends A
如何檢查在指定的類漲跌互現什麼擴展性狀A(也可以是從0到許多)特質?
如何其他答案的混合
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)
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)
怎麼是這樣的:
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)
這僅着眼於那些直接由類傳入的實例實現的接口,但可以擴展到遞歸看建立繼承層次結構。
這看起來很像我的回答+一些樣板:) – 2010-05-12 15:41:08
@Kevin - 日期戳記說你的答案看起來像一個可怕很多像我的答案... :-P – 2010-05-12 16:19:18
這不是我看到,當我點「最新」:) – 2010-05-13 07:43:25
我曾想過這種明顯的方法,但決定在這裏提出,因爲特質,因爲我知道在複雜的方式進行編譯。 – Jeriho 2010-05-11 15:01:11
當語言功能足夠時,千萬不要訴諸反思。 – 2010-05-11 15:11:57
同意。我第一次使用isInstanceOf - 這回答了他的問題的主體。但是當我重新閱讀他的實際問題標題「如何獲得特徵列表......」時,我轉而使用getInterfaces。 – 2010-05-11 15:14:52