Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 164 ]

Groovy reflection shortcuts

Groovy, as we would expect by now, provides shortcuts that let us reflect classes
easily. In Groovy, we can shortcut the getClass() method as a property access
.class, so we can access the class object in the same way whether we are using
the class name or an instance. We can treat .class as a string and print it directly
without calling Class.getName(), as follows:


The variable greeting is declared with a dynamic type, but has the type
java.lang.String after the Hello string is assigned to it. Classes are first class
objects in Groovy so we can assign a string to a variable. When we do this, the object
that is assigned is of the type java.lang.Class. However, it describes the String
class itself, so printing will report java.lang.String.


Groovy also provides shortcuts for accessing packages, methods, fields, and just
about all the other reflection details that we need from a class. We can access these
straight off the class identifier, as follows:


println "Package for String class"
println " " + String.package
println "All methods of Object class:"
Object.methods.each { println " " + it }
println "All fields of Integer class:"
Integer.fields.each { println " " + it }

Incredibly, these six lines of code do all of the same work as the 30 lines in our
Java example. If we look at the preceding code, it contains nothing that is more
complicated than it needs to be. Referencing String.package to get the Java
package of a class is as succinct as you can make it. As usual, String.methods and
String.fields return Groovy collections, so we can apply a closure to each element
with the each method. What's more, the Groovy version outputs a lot more useful
detail about the package, methods, and fields.


When using an instance of an object, we can use the same shortcuts through the
class field of the instance:


given:
def greeting = "Hello"
expect:
greeting.class.package == String.package
String.package.toString().contains "package java.lang"

http://www.ebook3000.com
Free download pdf