Java Annotations Tutorial for Beginners with Example

Java Annotations are a kind of meta-data, about elements of your code.
English definition of annotation is “footnote”/”explanation”, which means this is a explanation about your program elements .

The great myth behind why @ symbol was chosen for annotations.
@: AT: Annotation Type


The annotation type has all the features equal to that of an interface, exceptions are
1) Specifying @ symbol before interface keyword
2) Allowing of default values to its methods

It can in general give information about who was the author, what time it was coded, which year a bug was introduced in it , how many days they took to fix it up etc. .

Read Also :      How to create Custom Annotation in java

                         Top 10 most frequently used Annotation  Examples


Types of Annotations
Broadly annotations can be classified as,
  •     Annotations that can be applied to program elements
  •     Annotations that can be applied to other annotations 

  1. Annotations that can be applied to program elements:
 These are annotations that are applied to user programs .
 These annotations can further be classified as
  •     Annotations provided by the java team 
  •     Annotations we create as a programmer for our application                 

    2.  Annotations that can be applied to other annotations:



These in general configure annotations instead of program elements

The configurations that can be applied for an annotation are as follows,

        @Target:

This is an annotation that lets you know to which programmatic elements a given annotation can be   applied to. Example here may be you can configure an annotation to be used only for fields, to be used only for methods, and those that can be used only for classes.
The various programmatic elements that can be configured are generally represented as ElementType.



      @Retention:

This tells us until when a given annotation can be retented (retained).
The options we have is

*    To discard the annotation at the source code itself
*    To keep the annotation until the runtime.

     @Documented

The tool Sun Microsystems provides for documentation is the “javadoc” tool.
javadoc is a Documentation Generator from Sun Microsystems for generating API documentation in HTML format from Java source code.
A Documentation Generator is a programming tool that generates software documentation intended for programmers (API documentation) or end users (End-user Guide), or both, from a set of specially commented source code files
An application programming interface (API) is a protocol intended to be used as an interface by software components to communicate with each other.


Examples on Annotations
 
  1. Annotations that can be applied to program elements:

     @Deprecated:
     This marks the function as obsolete (to be old/will be removed).


Step 1:

Create a class as below, in the package com.sample.annotation


package com.sample.annotation;
public class ClassThatContainsTheDeprecatedMethod {
    @Deprecated  /*This marks the “deprecatedMethod” as a deprecated method. 
                   Definition of Deprecated: Said of a construct in a 
                   computing language considered old and planned
                   to be removed out, but still available for use. 
                   Deprecated is from java.lang hence no import required.
                   */
 
 public void deprecatedMethod() {
    }
}


Step 2:

Call above mentioned deprecatedMethod() by creating object of the class containing it .


 package com.sample.annotation;
public class Sample {
    public static void main(String args[]) {
        ClassThatContainsTheDeprecatedMethod obj = 
                                 new  ClassThatContainsTheDeprecatedMethod ();
        obj.deprecatedMethod (); /* Observe that this
                                    uses the above deprecated method.
                                     */
     }
}


Step 3:

Compile the above program using javac command


javac com\sample\annotation\*.java


Step 4:

When you compile, you get the compiler output as,

      Note: com\sample\annotation\Sample.java uses or overrides a deprecated API.
      Note: Recompile with -Xlint:deprecation for details.




Step 5:

Now, compile it with, the below command


javac Xlint com\sample\annotation\*.java


The warnings are displayed, as below ,


com\sample\annotation\Sample.java:9: warning: [deprecation] deprecatedMethod() in ClassThatContainsTheDeprecatedMethod has been deprecated
                obj.deprecatedMethod();
                   ^
1 warning



    2.  Annotations that can be applied to other annotations:

        @Documented

package com.sample.annotation;
import java.lang.annotation.Documented;
@Documented
public @interface MySampleAnnotation {
    public String name();
    public int age();
}

Now execute javadoc for the java program that uses the above annotation as,

javadoc com\sample\annotation\MySampleAnnotationClient.java


        @Target


package com.sample.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target (value = ElementType.TYPE)
public @interface MySampleAnnotation {
    public String name();
    public int age();
}


        @Retention


package com.sample.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MySampleAnnotation {
    public String name();
    public int age();
}


This means that it is available during actual execution of the program (through reflection).
We shall now change your “MySampleAnnotationClient” program as below,


 package com.sample.annotation;

import java.lang.reflect.Method;

public class MySampleAnnotationClient {
    public static void main(String args[]) {
        Method method = null;
        MySampleAnnotationClient mySampleAnnotationClient = null;
        MySampleAnnotation mySampleAnnotation = null;
        try {
            mySampleAnnotationClient = new MySampleAnnotationClient();
            method = mySampleAnnotationClient.getClass().getMethod("myMethod");
            mySampleAnnotation = method.getAnnotation(MySampleAnnotation.class);
            System.out.println(mySampleAnnotation.name());
            System.out.println(mySampleAnnotation.age());
            } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    @MySampleAnnotation(name="Sreenivasan Arumugam", age=29)
    public void myMethod() {
        System.out.println("I am the king with the MySampleAnnotation");
    }
}

Outputs :

Sreenivasan Arumugam  29


ONE LAST BUT NOT THE LEAST POINT

One more thing to know is that, each and every type of annotation has  Annotation  as parent class .Annotation class exists in  the java.lang.annotation package .

java annotations


About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry