Monday 13 January 2020

Get Generic type of a list


Below snippet prints generic type of a field.
public static void printGenericType(Field field) {
 ParameterizedType genericType = (ParameterizedType) field.getGenericType();

 int lengthOfArguments = genericType.getActualTypeArguments().length;

 System.out.println(field.getName() + " has " + lengthOfArguments + " arguments");
 for (int i = 0; i < lengthOfArguments; i++) {
  Class<?> typeArgument = (Class<?>) genericType.getActualTypeArguments()[i];
  System.out.println("\t" + i + "th argument : " + typeArgument);
 }

 System.out.println();
}


For example DemoCollection define two lists and one map.
public class DemoCollection {
 private List<String> strList;
 private List<Double> doubleList;
 private Map<String, Integer> myMap;
}

Below snippet prints generic type of the list 'strList'.
Field field = DemoCollection.class.getDeclaredField("strList");
printGenericType(field);


DemoCollection.java
package com.sample.app;

import java.util.List;
import java.util.Map;

public class DemoCollection {
 private List<String> strList;
 private List<Double> doubleList;
 private Map<String, Integer> myMap;
}


App.java
package com.sample.app;

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

public class App {

 public static void printGenericTypes(Class<?> clazz) {
  Field[] fields = clazz.getDeclaredFields();

  for (Field field : fields) {

   printGenericType(field);
  }

 }

 public static void printGenericType(Field field) {
  ParameterizedType genericType = (ParameterizedType) field.getGenericType();

  int lengthOfArguments = genericType.getActualTypeArguments().length;

  System.out.println(field.getName() + " has " + lengthOfArguments + " arguments");
  for (int i = 0; i < lengthOfArguments; i++) {
   Class<?> typeArgument = (Class<?>) genericType.getActualTypeArguments()[i];
   System.out.println("\t" + i + "th argument : " + typeArgument);
  }

  System.out.println();
 }

 public static void main(String... args) throws Exception {
  printGenericTypes(DemoCollection.class);

  System.out.println("***************************");
  Field field = DemoCollection.class.getDeclaredField("strList");
  printGenericType(field);
 }

}


Run App.java, you will get below messages in console.
strList has 1 arguments
 0th argument : class java.lang.String

doubleList has 1 arguments
 0th argument : class java.lang.Double

myMap has 2 arguments
 0th argument : class java.lang.String
 1th argument : class java.lang.Integer

***************************
strList has 1 arguments
 0th argument : class java.lang.String

You may like

No comments:

Post a Comment