Defining annotations

3 May 2008

It is right to say that a typical application programmer won’t need to define annotations in normal routine. But still, one should know how to define annotations.

Annotation type declarations are very much like normal interface declarations. An at-sign (@) comes before the interface keyword and each method declaration defines an element of the annotation type. Method declarations should not have any parameters or a throws clause. Also note that the return type should be amoung the following:
String, Class, enums, annotations, and arrays of the preceding types

Example:

    /**
     * Describes the Request-For-Enhancement(RFE) that led
     * to the presence of the annotated API element.
     */
    public @interface RequestForEnhancement {
        int    id();
        String synopsis();
        String engineer() default "[unassigned]"; 
        String date();    default "[unimplemented]"; 
    }

After defining the annotation, you can use it to annotate declarations. It is right to say that an annotation is a special kind of modifier, and it can be used anywhere same as public, static, or final can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants.

Here is a method declaration with an annotation corresponding to the annotation type declared above:

    @RequestForEnhancement(
        id       = 2868724,
        synopsis = "Enable time-travel",
        engineer = "Mr. Peabody",
        date     = "4/1/3007"
    )
    public static void travelThroughTime(Date destination) { ... }
 
An annotation type with no elements is termed a marker annotation type, for example:
 
    /**
     * Indicates that the specification of the annotated API element
     * is preliminary and subject to change.
     */
    public @interface Preliminary { }

del.icio.us:Defining annotations  digg:Defining annotations  spurl:Defining annotations  wists:Defining annotations  simpy:Defining annotations  newsvine:Defining annotations  blinklist:Defining annotations  furl:Defining annotations  reddit:Defining annotations  fark:Defining annotations  blogmarks:Defining annotations  Y!:Defining annotations  smarking:Defining annotations  magnolia:Defining annotations  segnalo:Defining annotations  gifttagging:Defining annotations

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Defining annotations

Leave a Reply