Tuesday, December 23, 2008

Annotations

 

­          Annotations provide a well-defined metadata mechanism

­          Metadata typically makes statements about source code that is interpreted at some point - usually by a code or data analysis tool

­          Annotations are modifiers that can be applied to package and type declarations, constructors, methods, fields, parameters and even variables

­          They take the form of name=value pairs, and we can use Java's built-in types, as well as define custom annotation types of our own.

­          Annotation type is a specific name of an annotation, along with any default values and related information

­          An annotation then uses an annotation type to associate some piece of information with a Java program element – methods, classes, variables etc.

­          So a class might only use one annotation type – like Override, and yet have ten or fifteen annotations – if it used Override ten or fifteen times

­          In short, annotation type refers to the definition of the annotation, while annotation refers to the actual usage of the definition.

­           

­          Annotations are checked by the Java compiler – we cannot misspell an annotation name or a member name of the annotation

­          The compiler will complain about the misspelling

­           

­          Standard annotation type

­          There are three standard annotations - all three are defined in the java.lang package:

o        @Override - used to indicate that a method overrides a method in its superclass

@Override

public String toString() {

      return super.toString() + “[modified by subclass]”;

}

o        @Deprecated - indicates that use of a method or element type is discouraged

@Deprecated

Public class Betamax { ... }

o        @SuppressWarnings - turns off compiler warnings for classes,  methods, or field and variable initializers

@SupressWarnings(“unchecked”)

public void method1() { …. }

­           

­          In addition to the three standard annotation types, there are three categories of annotations

o        Marker annotations – they are used with annotation types that define no members

They simply provide information contained within the name of the annotation itself - @MarkerAnnotation

An annotation whose members all have default values can also be used as a marker, since no information must be passed in

o        Single-value annotations – they have just a single member, named value. The format of a single-value annotation is - @SingleValueAnnotation(“some value”)

o        Full annotations – it isn’t really a category, it just uses the full range of annotation syntax

Here parentheses follow the annotation name, and all members are assigned values

        @Reviews({ //curly braces indicate an array of values

@Review(grade=”EXCELLENT”, reviewer=”df”),

@Review(grade=”SATISFACTORY”, reviewer=”eg”)})

­          There are no semicolons at the end of annotation lines

­           

­          Custom annotation type

­          Java allows us to define our own annotations with the @interface keyword

­          Annotation types are, at their basic level, Java interfaces

­          They look similar to a normal Java interface definition, but we use the @interface keyword instead of interface, which tells the compiler that we’re writing an annotation type instead of a normal interface

­          Following is a simple marker annotation type

package com.myapp;

public @interface InProgress { }

­          We can use this on any method or class

@com.myapp.InProgress

public void calculateInterest(float amount, float rate) {

}

­           

­          Following is a simple single-value annotation

package com.myapp;

public @interface TODO {

      String value();

}

­          Here value is not just a member declaration, but also a method declaration

­          We are actually defining a method called value(), and the compiler then automatically creates a member variable with the same name

­          Also, since the annotation types function like interfaces, the methods are all implicitly abstract, and have no bodies

­          This annotation can be used as follows

@TODO(value=”test”)

public void method1() { }

­          Or we can use the shorthand method that is applicable to single-value annotations

@TODO(“test”)

public void method1() { }

­           

­          Following is an annotation with multiple members

package com.myapp;

 

import java.util.Date;

 

public @interface GroupTODO {

      public enum Severity {CRITICAL, IMPORTANT, TRIVIAL};

     

      Severity severity() default Severity.IMPORTANT;

      Strint item();

String assignedTo();

String dateAssigned();

}

­          Any data type including enums can be used as a member of an annotation type

­          In the above example the member severity has a default value

­          The above annotation type can be used as follows

@GroupTODO( severity=GroupTODO.Severity.CRITICAL,

            item=”Calculate interest per month”,

            assignedTo=”Fred”,

            dateAssigned=”12/23/2008”)

public void calculateInterest(float amount, float rate) {

}

­           

­          The @interface keyword implicitly indicates an extension of java.lang.annotation.Annotation

­          So we can’t compile an annotation type that explicitly tries to extend anything else

­          However, we can extend and implement annotation types, although these extensions and implementations are not treated as annotation types

­           

No comments: