希望這會有所幫助。我仍然覺得有一種更加不自然的方式。嘗試使用collectInheritedMethods()
來查看你是否得到你想要的。我故意希望返回一個匹配方法列表,而不僅僅是一個標誌,因爲您還可以看到從超類實現的方法,列表中的Groovy真值(if(collectInheritedMethods(..))
)足以用於標記。
abstract class Parent {
void method1() { println "No Param" }
void method1(def a) { println "param: $a" }
void method1(List a, Map b) { println "param: $a and $b" }
}
class Child extends Parent {
void method1() { println "A: no param" }
void method1(def a) { println "A: param $a" }
void method1(def a, def b) { println "A: param $a and $b" }
}
List collectInheritedMethods(Class parent, Class child) {
List inheritedMethods = []
def parentMethods = parent.declaredMethods.findAll { !it.synthetic }
def childMethods = child.declaredMethods.findAll { !it.synthetic }
for(chMet in childMethods) {
for(paMet in parentMethods) {
if(chMet.name == paMet.name &&
chMet.parameterTypes == paMet.parameterTypes &&
chMet.returnType == paMet.returnType) {
inheritedMethods << child.getMethod(chMet.name,
chMet.parameterTypes)
.toGenericString()
//if only a flag is required to check if method implemented
//flag = true
//break
}
}
}
//Groovier way
/*inheritedMethods = childMethods.findAll { chMet ->
parentMethods.findAll { paMet ->
chMet.name == paMet.name &&
chMet.parameterTypes == paMet.parameterTypes &&
chMet.returnType == paMet.returnType
}
}*/
inheritedMethods
}
assert collectInheritedMethods(Parent, Child) ==
["public void Child.method1()",
"public void Child.method1(java.lang.Object)"]