Friday, May 27, 2011

Java Annotations


Hi Folks,
               This is technical one. You may think for a while “What the *$#*# is this? Arvind writing technical post?!?!? ” No wonder, I am writing it. And this post I dedicate to my trainer Arun who provided us this wonderful notes regarding Annotations. Its about Java Annotations. Come on, Lets dig deep into it.
WHAT IS ANNOTATION ?
               Annotations are like meta-tags that you can add to your code and apply them to package declarations, type declarations, constructors, methods, fields, parameters, and variables. Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program.
THE BASICS               There are two things you need to consider with annotations.
                       One is the “annotation” itself.
                       Another is the “annotation type“.

              An “annotation” is the meta-tag that you will use in your code to give it some life. An “annotation type” is used for defining an annotation. You will use it when you want to create your own custom annotation(User defined). First we shall see how to use the “annotation” and then we shall see how to use “annotation type” (writing user defined annotation).
PREDEFINED ANNOTATIONS
                Lets have a look at the predefined Annotations in java.lang package.
An annotation always begins with @ symbol
                 @Deprecated
                 @Override
                 @SuppressWarnings

In java.lang.annotation package, these annotations are called as “Meta – Annotations”.
 Meta – Annotations : Meta-annotations, which are actually known as the annotations of annotations, contain four types
                 @Target
                 @Retention
                 @Documented
                 @Inherited


USES OF ANNOTATION
            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.
How the Java compiler tool uses it?
Example 1:               Let’s start with the predefined annotation @Deprecated defined in java.lang package.
                   Class DeprecatedDemo{
                   @Deprecated
                    static void deprecatedMethod() { }
                   }
                    Class  TestDeprecatedAnnotation{
                    public static void main(String args[]) {
                    DeprecatedDemo. deprecatedMethod();
                    }
                    }

                Whenever you invoke the deprecatedMethod() from any program then the compiler “generates a warning “ when the program is compiled.
Example 2 :               @Override – the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass, it helps to prevent errors.
                   @Override
                   int overriddenMethod() {
                    ……………………………….. // some code
                   return 100;
                   }

                If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
Example 3:             @SuppressWarnings—the @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. In the example below, a deprecated method is used and the compiler would normally generate a warning. In this case, however, the annotation causes the warning to be suppressed.
                   @SuppressWarnings(”deprecation”)
                   void useDeprecatedMethod() {
                   DeprecatedDemo. deprecatedMethod();    //deprecation  warning - suppressed
                   } 


ANNOTATION TYPES -BASICS                                           
               An annotation defitype nition takes an “at” (@) sign, followed by the interface keyword plus the annotation name. Additionally, you can put data within parenthesis after the annotation name.
 Example to Define an Annotation (Annotation type)                   public @interface MyAnnotation {
                   String doSomething();
                   }

 Example to Annotate Your Code (Annotation)
                   @MyAnnotation (doSomething=”What to do”)
                   public void mymethod() { …. }

ANNOTATION TYPES
                 There are three annotation types:
                    Marker
                    Single-Element
                    Full-value or multi-value

Marker Annotation Type
            Marker: Marker type annotations have no elements, except the annotation name itself.
 Example :
                   public @interface MyAnnotation
                   { }

 Usage :
                   @MyAnnotation
                    public void myMethod()
                    { …. }

Single-Element Annotation type
          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.
 Example:
                   public @interface MyAnnotation {
                   String doSomething();
                   }

     Usage:
                  @MyAnnotation (”What to do”)
                   public void mymethod() { …. }

Multi-value Annotation type
          Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.
 Example:                   public @interface MyAnnotation {
                   String doSomething();
                   int count;
                   String date();
                   }

 Usage:
                  @MyAnnotation (doSomething=”What to do”, count=1, date=”09-09-2005″)
                   public void mymethod() { …. }

Rules of Thumb for Defining Annotation Type
     Here are some rules-of-thumb when defining an annotation type:
                    Annotation declaration should start with an ‘at’ sign like @, following with an interface keyword, following with the annotation name.
                    Method declarations should not have any parameters.
                    Method declarations should not have any throws clauses.
                    Return types of the method should be one of the following:
                              primitives
                              String
                              Class
                              enum
                              array of the above types

META ANNOTATION EXPLAINED
@Target  - The target annotation indicates the targeted elements of a class in which the annotation type will be applicable.
                           @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
             Where ElementType is an enum in java.lang.annotation package. The constants of this enumerated type provide a simple classification of the declared elements in a Java program.
Example :
                          @Target(ElementType.METHOD)
                           public @interface Test_Target {
                           public String doTestTarget();
                           }

            Next, create a class that will use the @Test_Target annotation.
                           public class TestAnnotations {
                           public static void main(String arg[]) {
                           new TestAnnotations().doTestTarget();
                           }

                           @Test_Target(doTestTarget=”Hello World !”)
                           public void doTestTarget() {
                           System.out.printf(”Testing Target annotation”);
                           }
                           }

            The @Target(ElementType.METHOD) indicates that this annotation type can be used to annotate only at the method levels. If you compile the preceding code, no warning messages will be shown.
@Retention  - The retention annotation indicates where and how long annotations with this type are to be retained.
           There are three values:
                         RetentionPolicy.SOURCE—Annotations with this type will be 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 .

 Example :

                       @Retention(RetentionPolicy.RUNTIME)
                        public @interface Test_Retention {
                        String doTestRetention();
                        }

          In this example, the @Retention(RetentionPolicy.RUNTIME) annotation indicates that your @Test_Retention annotation will be retained by the VM so that it can be read reflectively at run-time.
 Note  -  The concept of using annotations at runtime using reflection is explained in the later part of this post.
 @Documented - 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.
 Example :
              @Documented
               public @interface {
               String doTestDocument();
               }

               public class TestAnnotations {
               public static void main(String arg[]) {
               new TestAnnotations().doSomeTestRetention();
               new TestAnnotations().doSomeTestDocumented();
               }
               @Test_Retention (doTestRetention=”Hello retention test”)
                public void doSomeTestRetention() {
                System.out.printf(”Testing annotation ‘Retention’”);
                }
                @Test_Documented(doTestDocument=”Hello document”)
                public void doSomeTestDocumented() {
                System.out.printf(”Testing annotation ‘Documented’”);
                }
                }

          Note: javadoc is a tool used for generating html docs for Java classes.
@Inherited –  Indicates that an annotation type is automatically inherited
            This meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect. By default annotations are not inherited.
    Example :
                          @MyAnnotation class Super {
                           public void foo() {}
                           }
                           class Sub extends Super {
                           public void foo() {}
                           }

             If an annotation type 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.

References
http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/java/javaOO/annotations.html
http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/guide/language/annotations.html
http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm

            Thank you for reading this post and hope you all got a overview of what annotation is. Meet you all in my next post.

No comments:

Post a Comment

Share it if you like it