Monday 29 October 2012

Java Libraries Which Use Annotations

I recently added a command line user interface to my Java Thread Dump Analyser tool (Issue #2). As part of this work I tried out a new library that leveraged Java annotations in a nice way. This was the third library which I have encountered that uses annotations so I thought it might be useful to write a post about annotations and point out which Java libraries are putting them to good use.

Background

What are annotations? Annotations are user defined markers which can be used in Java source code to encode any kind of metadata. Here is a contrived example:

@RequestForEnhancement(
    id       = 2868724,
    synopsis = "Enable time-travel",
    date     = "4/1/3007"
)
public static void travelThroughTime(Date destination) { ... }

More information is available in the excellent Java documentation. It is interesting to note that Annotations get a better constructor syntax than the rest of the Java language including named parameters and default values.

(http://docs.oracle.com/javase/6/docs/technotes/guides/language/annotations.html)

JDO

My first contact with a library which makes extensive use of annotations was the use of JDO within Google App Engine. Once again I'll dive straight into an example:

@PersistenceCapable
public class Employee {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

    @Persistent
    private String name;
} 

What I like about this code is that the annotations provide a very concise way of marking which fields need to be stored and how they should be stored. The actual mechanics of storing and retrieving the data are then entirely generic and driven by the annotations which are used.

(https://developers.google.com/appengine/docs/java/datastore/jdo/dataclasses)

GSON

GSON is an excellent library for handling JSON serialization. By default it doesn't actually use Java annotations but the ExclusionStrategy API allows the user to define arbitrary logic for picking which fields to serialize. The docs include an example of how to use this API to select fields based on an annotation:

(https://sites.google.com/site/gson/gson-user-guide#TOC-User-Defined-Exclusion-Strategies)

JCommander

This command line argument parsing library uses annotations to simplify command line argument parsing. Here is a simple example:

public class JCommanderExample {
  @Parameter(names = { "-log", "-verbose" }, description = "Level of verbosity")
  private Integer verbose = 1;
 
  @Parameter(names = "-groups", description = "Comma-separated list of group names to be run")
  private String groups;
}

The online docs provide plenty of examples to get you started:

(http://jcommander.org/)