Tuesday 31 October 2017

How to access the annotation of a class using Java Reflection | Reflection in java


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

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

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation
    {

    }

@MyAnnotation
class Display
{
    public void showMessage()
    {
        System.out.println("Hi");
    }
}
ReflectionDemo.java
import java.lang.annotation.Annotation;

/**
 * 
 * We can access the class annotations of a class.
 *
 */
public class ReflectionDemo
{
    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)
        {
            System.out.println(annotation);
        }

    }

}
Output
@MyAnnotation()

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

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

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/eca56e82732b6bdecf5c1f7d98c23f5bc231a672/BasicJava/ReflectionDemo_access_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