Dienstag, 18. November 2008

Fun with annotations in Groovy/Griffon

The 1.6 version of Groovy seems to have full-fledged annotation support.

I took the occasion to finally learn to create some annotations on my own, and wrote an annotation which can be used in a Griffon model to give the controller some hints about how to best display its data.

I might have taken this a little bit too far, but it is also possible to declare strings in annotations which can later be evaluated.

Take this annotation as an example:


package annotations

import java.lang.annotation.*

@Retention(RetentionPolicy.RUNTIME)
public @interface TableModelInformation {
boolean displayed() default true
String displayName() default ""
String displayValue() default ""
}


This can be used in the model like this:


...
@TableModelInformation(displayValue='"Total Subprocesses: ${object.subprocesses.size()}"')
List subprocesses = []
...

(Note the weird string syntax: only double quotes (i.e. GString) are rightfully not interpreted as Strings. Furthermore it expects to receive an instance of the object in a variable named (tadaaa) "object".

This can be evaluated later in the controller:

return new GroovyShell(new Binding([object:object])).evaluate(object.class.getDeclaredField(field).getAnnotation(annotations.TableModelInformation).displayValue())

("object" and "field" are available in the context of the controller)

I am not sure how to optimize this code, especially the verbosity of annotation retrieval. It nevertheless is kind of funny to see groovy behavior in an (at least from me) unexpected way...

2 Kommentare:

Danno Ferrin hat gesagt…

This is exactly the approach I am lookin got take when full-blown form support comes into Griffon... one of these days. Annotating the data model with the data and then having the framework do all the heavy lifting.

Anonym hat gesagt…
Der Kommentar wurde von einem Blog-Administrator entfernt.