Jul 12 2008

Groovy Introspection, know what you have

Published by Kefah Issa at 9:31 am under groovy

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")

One Response to “Groovy Introspection, know what you have”

  1. computoriston 20 Aug 2008 at 1:30 am

    probably obvious but this technique can be applied to an class instance too

    s = “a string”
    s.class.methods.each {println it}

Trackback URI | Comments RSS

Leave a Reply