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 :


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

public class Employee {


public void getThisDone(){

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

Instance Variable
private Integer Id;

Custom Annotations

We can create our own annotations as well

public @interface Author {


Which can be used as:

public class Employee {


Annotations can have attributes too.
public @interface Author {

  String name();
  String date();
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;


  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