View RSS Feed

My Java Tips

Defining annotations

Rate this Entry
by , 11-07-2011 at 07:54 PM (1528 Views)
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


Java Code:
     * 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:

Java Code:
        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:
Java Code:
     * Indicates that the specification of the annotated API element
     * is preliminary and subject to change.
    public @interface Preliminary { }

Submit "Defining annotations" to Facebook Submit "Defining annotations" to Digg Submit "Defining annotations" to Submit "Defining annotations" to StumbleUpon Submit "Defining annotations" to Google

Tags: None Add / Edit Tags
Java SE