So I ended up with this solution, which does exactly what I wanted:
def pattern = ~/^public void ... $/
for(method in obj.metaClass.methods.findAll { it ==~ pattern })
{
/* Do some stuff... */
}
質問
I have two Groovy classes, Child1
and Child2
, which derive from an abstract parent class Parent
. The parent class implements three methods, only different in their parameters (i.e. their method names are the same).
Now I have an instance of the child class. The task is to check whether that object's class implements (overrides) one or more of the parent's methods.
I tried with Groovy's Inspector
on the child class object. This gives me a list of all methods, but I am not sure how to read the output. In particular I do not understand whether the method I am looking for is implement in the child class, or only in the parent class.
Can anybody help me with this, do I maybe need another way of introspection?
解決 2
So I ended up with this solution, which does exactly what I wanted:
def pattern = ~/^public void ... $/
for(method in obj.metaClass.methods.findAll { it ==~ pattern })
{
/* Do some stuff... */
}
他のヒント
Hope this helps. I still feel there is a groovier way. Try using collectInheritedMethods()
to see if you get what you wanted. I deliberately wanted to return a list of matched methods instead of just a flag because you can also see the methods that are implemented from super class, Groovy truth (if(collectInheritedMethods(..))
) on the list will be sufficient for flagging.
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)"]