Java Custom Annotations - Read using Reflection API

After reading this article , you will be able to create an Annotation in Java and Read the annotations using Java Reflection API.

Java Annotations can be created as follows :

@Retention(RetentionPolicy.RUNTIME) // makes the annotation available at runtime and can be read via reflection ( optional , but if not annotated with this, it cannot be read through reflection )
@Target(ElementType.Method) // Only Method's can be annotated ( optional )
public @interface MyAnnotation { // annotation declaration using @interface
// values of annotation
}

Custom Annotations Example :

 

Contents at glance

MyMethodAnnotation.java - Custom Annotation for methods
MyClassAnnotation.java - Custom Annotation for Class
MyClassWithAnnotations.java - Class having methods annotated with custom annotations
ReadAnnotationsUsingReflection.java - Read annotation using Java Reflection API

MyMethodAnnotation.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyMethodAnnotation {
    public String path();

    public String returnType() default "text";
}

MyClassAnnotation.java

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyClassAnnotation {
    String rootPath();

    String resourceName();
}

MyClassWithAnnotations.java

@MyClassAnnotation(resourceName = "Employee", rootPath = "employee")
public class MyClassWithAnnotations {

    @MyMethodAnnotation(path = "/getname", returnType = "json")
    public String getName() {
        return "{\"name\":\"Prashanth\"}";
    }

    @MyMethodAnnotation(path = "/getResourceType")
    public String getResourceType() {
        return "Employee";
    }
}

ReadAnnotationsUsingReflection.java

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReadAnnotationsUsingReflection {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException,
                    IllegalArgumentException, InvocationTargetException {

        Class<?> myClassWithAnnotations = MyClassWithAnnotations.class;

        // verify if class has annotated with "MyClassAnnotation"
        if (myClassWithAnnotations.isAnnotationPresent(MyClassAnnotation.class)) {

          // Read class annotation ( MyClassAnnotation )
          MyClassAnnotation classAnnotation = (MyClassAnnotation) myClassWithAnnotations
                            .getAnnotation(MyClassAnnotation.class);
          String rootPath = classAnnotation.rootPath();   // get rootPath of class using reflection
          System.out.println("Class : " + myClassWithAnnotations.getSimpleName() + " , rootPath = " + rootPath);

          // Read all method annotations ( MyMethodAnnotation )
          for (Method method : myClassWithAnnotations.getDeclaredMethods()) {     // iterate over all methods

             // verify if method is annotated with "MyMethodAnnotation"
             if (method.isAnnotationPresent(MyMethodAnnotation.class)) {

                // get annotation of method
                MyMethodAnnotation methodAnnotation = (MyMethodAnnotation) method
                                    .getAnnotation(MyMethodAnnotation.class);

                String path = methodAnnotation.path();     // get path using reflection
                String returnTyppe = methodAnnotation.returnType();      // get returnType using reflection

                String methodName = method.getName();     // get method using reflection

                System.out.println("method : " + methodName + " , path : " + path + " , returnType = "
                        + returnTyppe);
            }
        }
     }
  }
}

Class : MyClassWithAnnotations , rootPath = /employee
method : getName , path : /getname , returnType = json
method : getResourceType , path : /getResourceType , returnType = text

 

References :

https://docs.oracle.com/javase/tutorial/java/annotations/declaring.html

http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

https://docs.oracle.com/javase/tutorial/java/annotations/basics.html

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com