Monday 13 January 2020

How to get generic types of map in Java?


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 types of the map "myMap".
Field field = DemoCollection.class.getDeclaredField("myMap");
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("myMap");
  printGenericType(field);
 }

}


Output
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

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


You may like

No comments:

Post a Comment