Calling the static methods of a java/groovy object using reflection
groovy, java, reflection
Solution
Given:
class Test {
public static testThis() {
println "Called testThis"
}
public static woo() {
println "Called woo"
}
public static testOther() {
println "Called testOther"
}
}
You can do:
Test.metaClass.methods.grep { it.static && it.name.startsWith( 'test' ) }.each {
it.invoke( Test )
}
To print:
Called testOther
Called testThis
A more generic method to execute the static test methods of a class would be:
def invokeClass( clazz ) {
clazz.metaClass.methods.grep { it.static && it.name.startsWith( 'test' ) }.each {
it.invoke( clazz )
}
}
invokeClass( Test )
Problem
I'm working on a groovy unit-testing class that contains a collection of rules for whether or not the contents of a file are correctly formatted. (Not using a proper rules engine, it just takes advantage of Groovy's assertion capabilities to do validation in a way that vaguely resembles what a rules engine would do.) I was thinking that I could create a method called FireAllRules that looks like this: ``` public static void FireAllRules(File file) { for(def method in Class.getMethods) { if(method.name.indexOf("rule" == 0) method.invoke(file); } } ``` All the methods that I want the loop to pick up on are static, and I noticed during the debugging process none of my rule methods are included in the Class.getMethods() enumeration. Ideally, I would like to only loop over the methods that I personally wrote into the class rather than sorting through dozens of uninteresting methods that come in along with java.Object. Is there a way to use reflection to iterate over these static methods at runtime?