Thursday, September 2, 2010

Java Annotations Introduction

Annotations
Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.

Annotations have a number of uses, among them:
  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.
There are two types of annotations available:
  • Simple annotations: These are the basic types supplied with Tiger, which you can use to annotate your code only; you cannot use those to create a custom annotation type.
  • Meta-annotations: These are the annotation types designed for annotating annotation-type declarations. Simply speaking, these are called the annotations-of-annotations.
An annotation is the meta-tag that you will use in your code to give it some life.
Annotation type is used for defining an annotation.

Annotation Types
An
Annotation type definition takes an "at" (@) sign, followed by the interface keyword plus the annotation name.
 On the other hand, an annotation takes the form of an "at" sign (@), followed by the annotation type.

There are three annotation types:
  1. Marker: Marker type annotations have no elements, except the annotation name itself.
  2. Single-Element: Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.
  3. Full-value or multi-value: Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.

Example to Define an Annotation (Annotation type)

                public @interface MyAnnotation {

                          String doSomething();   
               }
Singel element Usage:
           MyAnnotation (doSomething="What to do") 
               public void mymethod() { .... }
multi-value  Usage
                     @MyAnnotation (doSomething="What to do", count=1,  date="09-09-2005")    
                    public void mymethod() {        ....     }  
Simple Annotations
There are three annotation types that are predefined by the language specification itself:        

      1. Deprecated
      2. Override
      3. Suppresswarnings
         @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a  warning  whenever a program uses a method, class, or field with the @Deprecated annotation.
        The Javadoc tag starts with a lowercase "d" and the annotation starts with an uppercase "D".    

 // Javadoc comment follows       
 /**        
 * @deprecated        
 * explanation of why it was deprecated        
 */       
 @Deprecated       
        static void deprecatedMethod() { }  
        @Override annotation informs the compiler that the element is meant to override an element declared in a superclass .   

 // mark method as a superclass method   
 // that has been overridden      
 @Override       
 int overriddenMethod() { }   
        @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.

          // use a deprecated method and tell      
   // compiler not to generate a warning      
   @SuppressWarnings("deprecation")       
   void useDeprecatedMethod() {           
    objectOne.deprecatedMethod(); 
    //deprecation warning - suppressed      
   }   

Meta-Annotations

Meta-annotations, which are actually known as the annotations of annotations, contain four types. These are:
  • Target
  • Retention
  • Documented
  • Inherited
The target annotation indicates the targeted elements of a class in which the annotation type will be applicable. It contains the following enumerated types as its value:
  • @Target(ElementType.TYPE)—can be applied to any element of a class
  • @Target(ElementType.FIELD)—can be applied to a field or property
  • @Target(ElementType.METHOD)—can be applied to a method level annotation
  • @Target(ElementType.PARAMETER)—can be applied to the parameters of a method
  • @Target(ElementType.CONSTRUCTOR)—can be applied to constructors
  • @Target(ElementType.LOCAL_VARIABLE)—can be applied to local variables
  • @Target(ElementType.ANNOTATION_TYPE)—indicates that the declared type itself is an annotation type
The retention annotation indicates where and how long annotations with this type are to be retained. In simple it indicates the scope of the annotation Type.
There are three values:
  • RetentionPolicy.SOURCE—Annotations with this type will be by retained only at the source level and will be ignored by the compiler
  • RetentionPolicy.CLASS—Annotations with this type will be by retained by the compiler at compile time, but will be ignored by the VM
  • RetentionPolicy.RUNTIME—Annotations with this type will be retained by the VM so they can be read only at run-time
The documented annotation indicates that an annotation with this type should be documented by the javadoc tool. By default, annotations are not included in javadoc. But if @Documented is used, it then will be processed by javadoc-like tools and the annotation type information will also be included in the generated document.

Inherited annotation

It is important to understand the rules relating to inheritance of annotations, as these have a bearing on join point matching based on the presence or absence of annotations.
By default annotations are not inherited.The annotation used on the super class doesn't get inherited to sub class,unless the annotation (@MyAnnotation used in the following example)used on super class has the @Inherited meta-annotation.
Annotation are not be inheritable in case of  extending Interface even if they have
@Inherited meta-annotation.

@MyAnnotation    
 class Super {      
  @Oneway public void foo() {}    
 }
 class Sub extends Super {
  public void foo() {}
 }    
Then Sub does not have the MyAnnotation annotation, and Sub.foo() is not an @Oneway method, despite the fact that it overrides Super.foo() which is.
If an annotation type @MyAnnotation has the meta-annotation @Inherited then an annotation of that type on a class will cause the annotation to be inherited by sub-classes. So, in the example above, if the MyAnnotation type had the @Inherited attribute, then Sub would have the MyAnnotation annotation.
@Inherited annotations are not inherited when used to annotate anything other than a type.
 A type that implements one or more interfaces never inherits any annotations from the interfaces it implements(they are inheritable only if subclass extends another super class).


        Every compiler warning belongs to a category. The Java Language Specification lists two categories: "deprecation" and "unchecked." The  "unchecked" warning can occur when interfacing with legacy code written before the advent of generics .

         To suppress more than one category of warnings, use the following syntax:
 @SuppressWarnings({"unchecked", "deprecation"}) 
 
Annotation Processing:
            The more advanced uses of annotations include writing an annotation processor that can read a Java program and take actions based on its             annotations.
            To make annotation information available at runtime, the annotation type itself must be annotated with @Retention(RetentionPolicy.RUNTIME),
            as follows:
 import java.lang.annotation.*;     
 @Retention(RetentionPolicy.RUNTIME)   
 @interface AnnotationForRuntime {       
  // Elements that give information              
  // for runtime processing       
 }    

Resources


4)Java Custom Annotations (Has good Example on Inherited meta-annotation)
http://technicalmumbojumbo.wordpress.com/2008/01/13/java-custom-annotations/

**********************************************************************************************************************************************