Tuesday, 7 November 2017

How to access the method parameter Annotation using Java Reflection | Reflection in java


Click here to watch in Youtube :
https://www.youtube.com/watch?v=BVR4NP9-jN0&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.PARAMETER)

@interface MyAnnotation
{
    public String name();

    public String value();
}

public class Display
{

    public void doSomething(@MyAnnotation(name = "age", value = "23") String value)
    {
    }
}
ReflectionDemo.java
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * Parameter Annotations:
 * 
 * We can access parameter annotations from the Method object like below.
 */
public class ReflectionDemo
{
    public static void main(String[] args)
    {
        try
        {
            Class<Display> classObj = Display.class;
            Method method = classObj.getMethod("doSomething", String.class);
            /*
             * Returns:a two-dimensional Annotation array, containing an 
             * array of annotations for each method parameter.
             */
            Annotation[][] parameterAnnotations = method.getParameterAnnotations();
            Class[] parameterTypes = method.getParameterTypes();

            int i = 0;
            for (Annotation[] annotations : parameterAnnotations)
            {
                Class parameterType = parameterTypes[i++];

                for (Annotation annotation : annotations)
                {
                    if (annotation instanceof MyAnnotation)
                    {
                        MyAnnotation myAnnotation = (MyAnnotation) annotation;
                        System.out.println("param: " + parameterType.getName());
                        System.out.println("name : " + myAnnotation.name());
                        System.out.println("value: " + myAnnotation.value());
                    }
                }
            }
        }
        catch (NoSuchMethodException e)
        {
            e.printStackTrace();
        }
    }

}
Output
param: java.lang.String
name : age
value: 23

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

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

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