Jul 12 2008
Groovy Introspection, know what you have
Lots of fun with Groovy introspection. Java already provides something similar but in Groovy it has completely different taste and use.
I actually use introspection often from within groovysh to investigate on what a class provides, just like auto-complete in modern IDE’s
// Whats is your class? a = 5 b = "Hello" println "Class of a : ${a.class} \nClass of b : ${b.class}" // Introspection, know all the details about classes : // List all constructors of a class String.constructors.each{println it} // List all interfaces implemented by a class String.interfaces.each{println it} // List all methods offered by a class String.methods.each{println it} // Just list the methods names String.methods.name // Get the fields of an object (with their values) d = new Date() d.properties.each{println it} // Not much related, but interesting : Dynamic Method calling class Greeting{ def sayHello(){ println "Hello, Stranger" } def sayHello(String name){ println "Hello, ${name}" } } g = new Greeting() s = "sayHello" g."${s}" ("Ali Baba")
probably obvious but this technique can be applied to an class instance too
s = “a string”
s.class.methods.each {println it}