Tuesday, 7 November 2017

How to access the class Annotation using Java Reflection | Reflection in java


Click here to watch in Youtube :
https://www.youtube.com/watch?v=MShc6rNWy1Y&list=UUhwKlOVR041tngjerWxVccw

Display.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)

@interface MyAnnotation
{
    public String name();

    public String value();
}

@MyAnnotation(name = "age", value = "23")
public class Display
{

}
ReflectionDemo1.java
import java.lang.annotation.Annotation;

/**
 * We can access the annotations of a class, method or field at
 * runtime. 
 * 
 * Class Annotations Example:
 */
public class ReflectionDemo1
{
    public static void main(String[] args)
    {
        Class<Display> classObj = Display.class;
        /*
         * Returns:annotations present on this element
         */
        Annotation[] annotationArray = classObj.getAnnotations();

        for (Annotation annotation : annotationArray)
        {
            if (annotation instanceof MyAnnotation)
            {
                MyAnnotation myAnnotation = (MyAnnotation) annotation;
                System.out.println("name: " + myAnnotation.name());
                System.out.println("value: " + myAnnotation.value());
            }
        }
    }

}
Output
name: age
value: 23

ReflectionDemo2.java
/**
 * We can access the annotations of a class, method or field at
 * runtime.
 * 
 * Class Annotations Example:
 */
public class ReflectionDemo2
{
    public static void main(String[] args)
    {
        Class<Display> classObj = Display.class;
        /*
         * Returns:this element's annotation for the specified
         * annotation type if present on this element, else null
         */
        MyAnnotation myAnnotation = classObj.getAnnotation(MyAnnotation.class);

        System.out.println("name: " + myAnnotation.name());
        System.out.println("value: " + myAnnotation.value());
    }

}
Output
name: age
value: 23

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/ReflectionDemo_access_class_annotation.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/ReflectionDemo_access_class_annotation

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/7b0b4fbacd011a10dc23b42c4acc3ae6988db782/BasicJava/ReflectionDemo_access_class_annotation/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment