Wednesday 8 November 2017

How to get the generic variable types using Java Reflection | Reflection in java


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

Display.java
import java.util.Arrays;
import java.util.List;

public class Display
{
    public List<String> nameList = Arrays.asList("Peter", "Juli", "Dave");
}

ReflectionDemo.java
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Generic Field Types:It is possible to access the generic types of public
 * fields.
 * 
 */
public class ReflectionDemo
{
    public static void main(String[] args)
    {
        try
        {
            Class<Display> classObj = Display.class;
            Field field = classObj.getField("nameList");
            Type genericFieldType = field.getGenericType();
            System.out.println("genericFieldType = " + genericFieldType);       
                        
            if (genericFieldType instanceof ParameterizedType)
            {
                ParameterizedType aType = (ParameterizedType) genericFieldType;
                Type[] fieldArgTypes = aType.getActualTypeArguments();
                for (Type fieldArgType : fieldArgTypes)
                {
                    Class fieldArgClass = (Class) fieldArgType;
                    System.out.println("fieldArgClass = " + fieldArgClass);
                    System.out.println( "fieldArgClass Name = " + fieldArgClass.getName());
                }
            }

        }
        catch (NoSuchFieldException | SecurityException e)
        {
            e.printStackTrace();
        }

    }

}
Output
genericFieldType = java.util.List<java.lang.String>
fieldArgClass = class java.lang.String
fieldArgClass Name = java.lang.String

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

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

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