Wednesday 8 November 2017

How to get the generic parameter types of method parameters using Java Reflection


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

Display.java
import java.util.List;

public class Display
{

    protected List<String> nameList;

    public void setNameList(List<String> nameList)
    {
        this.nameList = nameList;
    }

}
ReflectionDemo.java
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * We can access the generic parameter types of the method parameters
 */
public class ReflectionDemo
{
    public static void main(String[] args)
    {
        try
        {
            Class<Display> classObj = Display.class;
            Method method = classObj.getMethod("setNameList", List.class);
            Type[] genericParameterTypes = method.getGenericParameterTypes();

            for (Type genericParameterType : genericParameterTypes)
            {
                System.out.println("genericParameterType = "+genericParameterType);
                if (genericParameterType instanceof ParameterizedType)
                {
                    ParameterizedType aType = (ParameterizedType) genericParameterType;
                    Type[] parameterArgTypes = aType.getActualTypeArguments();
                    for (Type parameterArgType : parameterArgTypes)
                    {
                        Class parameterArgClass = (Class) parameterArgType;
                        System.out.println("parameterArgClass = " + parameterArgClass);
                        System.out.println("parameterArgClass Name = " + parameterArgClass.getName());
                    }
                }
            }
        }
        catch (NoSuchMethodException | SecurityException e)
        {
            e.printStackTrace();
        }

    }

}
Output
genericParameterType = java.util.List<java.lang.String>
parameterArgClass = class java.lang.String
parameterArgClass Name = java.lang.String

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

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

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

See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • 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