Saturday, August 23, 2014
Annotations is a form of meta-data to the Java code and doesn't directly impact the behavior of the code. This article covers key concepts around annotations in Java with examples.

Basic format of Annotation

The at sign @ indicates start of annotation. In the example below we use an annotation @SuppressWarnings with value of "deprecation". This annotation tells the compiler to suppress the display of specific warnings in this case deprecated.

@SuppressWarnings("deprecation")
public static void main(String[] args) {
  Employee e = new Employee();
  e.setId("100");
  e.setName("Employee1");
}

Predefined annotations in Java

Java defined few predefined annotations. These include @Deprecated, @SuppressWarnings and @Override.

@Deprecated annotation is used to mark an element as deprecated. When a element annotated as deprecated is used in a program compiler generates a warning.

@Deprecated
public void setId(String id) {
  this.id = id;
}

When a deprecated method is used in a program the compiler generates a warning as below.

The method setId(String) from the type Employee is deprecated

@SuppressWarnings annotation is used to suppress warnings which the compiler generates. For example, to suppress the deprecation warning generated by the previous example we could use this annotation.

@SuppressWarnings("deprecation")
public static void main(String[] args) {
  Employee e = new Employee();
  e.setId("100");
  e.setName("Employee1");
}

@Override annotation is used to indicate to the compiler that the element is overriding an element declared in a super class. Using @Override is not mandatory but helps to prevent errors like the case where super class method is not overridden correctly.

@Override
public void print() {
}

Custom annotations in Java

In Java it is possible to define our own custom annotation types. Annotation type definitions in Java are similar to interface type definitions except that the interface keyword is preceded with a @ (AT) sign.

Let us consider a quick example to create a class details annotation. To define this annotation we would do as below. Note that we can specify default values for elements as well in the annotation definition.

package com.sourcetricks.annotations;

@interface ClassDetails {
   String creator();
   String date();
   String revision() default "1.0";
}

To use the ClassDetails annotation with the required parameters on a Class we would do as below.

@ClassDetails(creator = "SourceTricks", date = "8/23/2014", revision = "1.0")
public class TestAnnotations {
}

Meta annotations in Java

Java also supports meta annotations. These are annotations that apply to other annotations. Let us look at some examples to understand this better.

@Retention annotation indicates how the marked element is stored. In this example we create a MethodNotes annotation with RetentionPolicy as RunTime. This would allow to examine the annotations in RunTime using reflection.

package com.sourcetricks.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MethodNotes {
   public String notes();
}

Let us create a simple Employee class and apply the MethodNotes annotation to functions in the class.

package com.sourcetricks.annotations;

public class Employee {

   private String id;
   private String name;

   public Employee(String id, String name) {
     this.id = id;
     this.setName(name);
   } 

   @MethodNotes(notes="Getter")
   public String id() { return id; }

   @MethodNotes(notes="Setter")
   public void setId(String id) {
     this.id = id;
   }
 
   @MethodNotes(notes="Getter")
   public String getName() {
     return name;
   }
 
   @MethodNotes(notes="Setter")
   public void setName(String name) {
     this.name = name;
   } 
 
   @MethodNotes(notes="print")
   public void print() { 
     System.out.println(id + ", " + name);
   }
}

Since we have added RunTime RetentionPolicy for MetaNotes annotation, we should be able to access the annotation notes in RunTime. In the code snippet below we print the annotation value using Reflection.

public class TestAnnotations {

   public static void main(String[] args) { 
      Employee e1 = new Employee("Emp100", "John");
      for ( Method m  : e1.getClass().getDeclaredMethods() ) {
         if ( m.isAnnotationPresent(MethodNotes.class) ) {
            MethodNotes methodNotes = m.getAnnotation(MethodNotes.class);
     System.out.println(m.getName() + " = " + methodNotes.notes());
 }
      }
   }
}

@Target annotation is used to restrict what type of elements the specific annotation can be applied to. In the example below we restrict the MethodNotes annotation only to ElementType of Method.

@Target(value = { ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MethodNotes {
 public String notes();
}

@Inherited is another meta annotation type. This applies only for class declarations. @Inherited indicates that annotation can be inherited from the super class.

@Documented meta annotation type is used to indicate to the JavaDoc tool that the element needs to be documented.

Continue to read other java tutorials from here.

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top