2014-02-27 32 views
1

問題如何在不使用Groovy繼承方法的情況下獲取類的所有方法名稱?

你怎麼能得到的類的所有方法的名字沒有繼承的方法?

def methods = MyClass.methods.collect { it.name } 
println methods.each { println it } 
assert ["method1_static_void", "method2_static_String", "method3_void", "method4_String"].sort() == methods.sort() 


class MyClass { 
    public static void method1_static_void() {} 
    public static String method2_static_String() {} 
    public void method3_void() {} 
    private String method4_String() {} 
} 

預期輸出

method1_static_void 
method2_static_String 
method3_void 
method4_String 

實際輸出

setProperty 
getProperty 
super$1$wait 
super$1$wait 
super$1$wait 
super$1$clone 
getMetaClass 
invokeMethod 
setMetaClass 
__$swapInit 
method3_void 
method1_static_void 
method2_static_String 
this$2$method4_String 
this$dist$invoke$1 
this$dist$set$1 
this$dist$get$1 
super$1$toString 
super$1$notify 
super$1$notifyAll 
super$1$getClass 
super$1$equals 
super$1$hashCode 
super$1$finalize 
wait 
wait 
wait 
equals 
toString 
hashCode 
getClass 
notify 
notifyAll 
[setProperty, getProperty, super$1$wait, super$1$wait, super$1$wait, super$1$clone, getMetaClass, invokeMethod, setMetaClass, __$swapInit, method3_void, method1_static_void, method2_static_String, this$2$method4_String, this$dist$invoke$1, this$dist$set$1, this$dist$get$1, super$1$toString, super$1$notify, super$1$notifyAll, super$1$getClass, super$1$equals, super$1$hashCode, super$1$finalize, wait, wait, wait, equals, toString, hashCode, getClass, notify, notifyAll] 
Assertion failed: 

assert ["method1_static_void", "method2_static_String", "method3_void", "method4_String"] == methods 
                          | | 
                          | [setProperty, getProperty, super$1$wait, super$1$wait, super$1$wait, super$1$clone, getMetaClass, invokeMethod, setMetaClass, __$swapInit, method3_void, method1_static_void, method2_static_String, this$2$method4_String, this$dist$invoke$1, this$dist$set$1, this$dist$get$1, super$1$toString, super$1$notify, super$1$notifyAll, super$1$getClass, super$1$equals, super$1$hashCode, super$1$finalize, wait, wait, wait, equals, toString, hashCode, getClass, notify, notifyAll] 
                          false 

個谷歌發現

回答

5

相反的:

def methods = MyClass.methods.collect { it.name } 

你只需要申報的非合成方法:

def methods = MyClass.declaredMethods.findAll { !it.synthetic }.name 
相關問題