Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 96 ]

We can implement a login action for our user controller in Grails—simply by
declaring a closure in the controller class and assigning it to a field called login.
In the UI, Grails provides tags to automatically create a link that will dispatch to our
login action:


<g:link controller="user" action="login">Login</g:link>

The Grails runtime can find the appropriate action, given the closure field name as a
string, and call that closure when the user clicks on the link. We can achieve the same
effect by simply using Java reflection:


class MyController {
def public myAction = {
println "I'm an action"
}
}

void callPublicClosureField(Class clazz, String closure ) {
def controller = clazz.newInstance()
controller.getClass()
.getDeclaredField(closure).get(controller).call()
}

callPublicClosureField(MyController.class, "myAction")

Grails 2.0 has added the ability to define Controller actions as
methods, and this is now the preferred method of defining actions.
It is still worth looking at how this technique works.

Here we are using Java reflection to access a public field in our controller class.
We then invoke this closure field with the call method. Java reflection honors class
visibility, so we need to make the field public in order to be able to access it. Later
in this book, we will explore other methods that allow us to access static and private
fields in both classes and scripts.


This gives the ability to write code like:


def something = {
snippet of code
}

Having a separate runtime that makes sense will be the key to writing some of our
DSLs later in the book.


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