I have a problem to get the type of a list. The problem is While declaring I'm not specifying the type. I'm setting it only at run time.
I have a POJO class
public class MyObject<T> {
private String name;
private List<T> list;
//getter and setter
}
I have followed this SO question and tried my below code
public class ListType {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
ListType listType = new ListType();
List<Integer> listInt = new ArrayList<Integer>();
MyObject<Integer> myObjectInt = new MyObject<Integer>();
myObjectInt.setList(listInt);
listType.initialize(myObjectInt);
MyObject<String> myObjectStr = new MyObject<String>();
List<String> listStr = new ArrayList<String>();
myObjectStr.setList(listStr);
listType.initialize(myObjectStr);
}
private void initialize(MyObject myObject) throws NoSuchFieldException, SecurityException {
List list = myObject.getList();
ListType listType = new ListType();
listType.getListType(list);
}
private void getListType(List list) throws NoSuchFieldException, SecurityException {
Field stringListField = MyObject.class.getDeclaredField("list");
ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
System.out.println(stringListClass);
}
}
Then I am getting following exception
Exception in thread "main" java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
at com.sample.listtype.ListType.getListType(ListType.java:35)
at com.sample.listtype.ListType.initialize(ListType.java:27)
at com.sample.listtype.ListType.main(ListType.java:15)
How to get the type if I'm setting at run time?