20.7.10

Annotations with Groovy

Introduction

Java 5 and above supports the use of annotations to include metadata within programs. Groovy 1.1 and above also supports such annotations.

Annotations are used to provide information to tools and libraries. They allow a declarative style of providing metadata information and allow it to be stored directly in the source code. Such information would need to otherwise be provided using non-declarative means or using external files. We won't discuss guidelines here for when it is appropriate to use annotations, just give you a quick run down of annotations in Groovy.

Annotations are defined much like Java class files but use the @interface keyword. As an example, here is how you could define aFeatureRequest Annotation in Java:

// Java
public @interface FeatureRequest {
String key();
String summary();
String assignee() default "[unassigned]";
String status() default "[open]";
String targetVersion() default "[unassigned]";
}

This annotation represents the kind of information you may have in an issue tracking tool. You could use this annotation in a Groovy file as follows:

@FeatureRequest(
key="GROOVY-9999",
summary="Support Graphical Annotations",
assignee="Pete",
status="Open",
targetVersion="5.0"
)
class SomeClassWhereFeatureCouldBeUsed {
// ...
}

Now if you had tools or libraries which understood this annotation, you could process this source file (or the resulting compiled class file) and perform operations based on this metadata.

As well as defining your own annotations, there are many existing tools, libraries and frameworks that make use of annotations. See some of the examples referred to at the end of this page. As just one example, here is how you could use annotations with Hibernate or JPA:

import javax.persistence.*

@Entity
@Table(name="staff")
class Staff implements Serializable {
@Id @GeneratedValue
Long id
String firstname
String lastname
String position
}

Example

As another example, consider this XStream example. XStream is a library for serializing Java (and Groovy) objects to XML (and back again if you want). Here is an example of how you could use it without annotations:

// require(groupId:'com.thoughtworks.xstream', artifactId:'xstream', version:'1.3')
import com.thoughtworks.xstream.*

class Staff {
String firstname, lastname, position
}

def xstream = new XStream()
xstream.classLoader = getClass().classLoader
def john = new Staff(firstname:'John',
lastname:'Connor',
position:'Resistance Leader')

println xstream.toXML(john)

This results in the following output:

<Staff>
<firstname>John</firstname>
<lastname>Connor</lastname>
<position>Resistance Leader</position>
</Staff>

Just as an aside, not related to annotations, here is how you could write the XML to a file:

new File("john.xml").withOutputStream { out ->
xstream.toXML(john, out)
}

And how you would read it back in:

// require(groupId:'com.thoughtworks.xstream', artifactId:'xstream', version:'1.3')
// require(groupId:'xpp3', artifactId:'xpp3_min', version:'1.1.4c')
import com.thoughtworks.xstream.*

class Staff {
String firstname, lastname, position
}

def xstream = new XStream()
def john
// now read back in
new File("john.xml").withInputStream { ins ->
john = xstream.fromXML(ins)
}

println john.dump()
// => <Staff@12d96f2 firstname=John lastname=Connor position=Resistance Leader>

Now, on to the annotations ...

XStream also allows you to have more control over the produced XML (in case you don't like its defaults). This can be done through API calls or with annotations. Here is how we can annotate our Groovy class with XStream annotations to alter the resulting XML:

// ...
import com.thoughtworks.xstream.annotations.*

@XStreamAlias("person")
class Associate {
@XStreamAsAttribute
@XStreamAlias('first-name')
String firstname

@XStreamAlias('surname')
String lastname

@XStreamOmitField
String position
}

msg = new Associate(firstname:'Sarah',
lastname:'Connor',
position:'Protector')
Annotations.configureAliases(stream, Associate)
println stream.toXML(msg)

When run, this produces the following output:

<person first-name="Sarah">
<surname>Connor</surname>
</person>

Differences to Java

Annotations may contain lists. When using such annotations with Groovy, remember to use the square bracket list notation supported by Groovy rather than the braces used by Java, i.e.:

// Java
@ManagedOperationParameters({
@ManagedOperationParameter(name="x", description="The first number"),
@ManagedOperationParameter(name="y", description="The second number")})

Would become:

// Groovy
@ManagedOperationParameters([
@ManagedOperationParameter(name="x", description="The first number"),
@ManagedOperationParameter(name="y", description="The second number")])

 


 


http://groovy.codehaus.org/Annotations+with+Groovy

No comments: