Tuesday, 10 May 2016

Java Annotations

Annotations were a feature introduces in Java 5. By the way the current version of java is 8.

Annotations tell the compiler about additional information.

Annotations commonly used are :

@Entity
@RequestMapping



Annotations can be applied to class, method, method parameter and instance variable


Class
@Resource
public class Employee {

}

Method
@Override
public void getThisDone(){
}

Parameter
public void getThisDone(@RequestParam("username") String userName){
 
}

Instance Variable
@Id
private Integer Id;


Custom Annotations

We can create our own annotations as well

public @interface Author {

}

Which can be used as:

@Author
public class Employee {

}

Annotations can have attributes too.
public @interface Author {

  String name();
  String date();
}
@Author(name="Hunaid",date="12-12-2016")
public class Employee {

}


Now suppose you want to know the name of authors for all the classes created in the project. This can be done using reflection.

Now, how to use these annotations?
We can use reflection to get the list of annotations on a class

package annot;

import java.lang.annotation.Annotation;

public class TestAnnotations {

 
 public static void main(String[] args) {
  Class aClass = Employee.class;

  System.out.println(aClass);

  Annotation[] annotations = aClass.getDeclaredAnnotations();
  for(Annotation annotation : annotations){
      if(annotation instanceof Author){
       Author myAnnotation = (Author) annotation;
          System.out.println("name: " + myAnnotation.name());
          System.out.println("value: " + myAnnotation.date());
      }
  }

 }
}
class annot.Employee
name: Hunaid
value: 12-12-2016

No comments:

Post a Comment

Share the post