Search

Dark theme | Light theme

December 5, 2009

Groovy Goodness: Know More About a Class

In Groovy we can use the Java reflection API to examine our classes. Groovy makes it a bit easier because we can access properties the Groovy way. And because we can call methods and properties directly on the class instead of the class property. We can still go the route through the class property, but it is optional.

interface Simple {}
class Sample implements Simple {
    String info
    String displayInfo() { "info from $Sample.name" }
}

assert 'Sample' == Sample.name
assert 'Sample' == Sample.class.name

def interfaces = Sample.interfaces.name
assert 'Simple' in interfaces
assert 'groovy.lang.GroovyObject' in interfaces

def methods = Sample.methods.name
assert 'setInfo' in methods
assert 'getInfo' in methods
assert 'displayInfo' in methods

def s = new Sample()
assert 'info from Sample' == s.displayInfo()