The following is a program that dynamically calls all the getXXX
methods on an object of CLASS
, where the CLASS
-name gets passed via command-line. And it works just fine.
// Program: callAllMethods.groovy
// Invoke this program as: groovy callAllMethods Date
args.each { arg ->
println "Methods of ${arg} ..."
def code = """
x = new ${arg}()
x.class.methods.each { f ->
if (f.name.startsWith("get")) {
print "new ${arg}()." + f.name + ": " + f.invoke(x)
println ''
}
}
"""
evaluate("$code")
println ''
}
However, when I try the simpler style of dynamic-method invocation (that does not use METHOD.invoke(OBJECT)
but rather OBJECT."METHOD-NAME"()
), like so,
// Program: callAllMethods.groovy
// Invoke this program as: groovy callAllMethods Date
args.each { arg ->
println "Methods of ${arg} ..."
def code = """
x = new ${arg}()
x.class.methods.each { f ->
if (f.name.startsWith("get")) {
result = x."${f.name}"()
println "new ${arg}().${f.name}: ${result}"
}
}
"""
evaluate("$code")
println ''
}
... I get the following error:
$ groovy callGetMethods.groovy Date
Methods of Date ...
Caught: groovy.lang.MissingPropertyException: No such property: f for class: callGetMethods
groovy.lang.MissingPropertyException: No such property: f for class: callGetMethods
at callGetMethods$_run_closure1.doCall(callGetMethods.groovy:13)
at callGetMethods.run(callGetMethods.groovy:10)
I cannot understand why! Groovy version that I'm using:
$ groovy -version
Groovy Version: 2.1.3 JVM: 1.6.0_43 Vendor: Sun Microsystems Inc. OS: Linux