lundi 12 janvier 2015

Get the list reference type

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 {

private String name;
private List 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> list = new ArrayList<Integer>();
MyObject myObject = new MyObject();
myObject.setList(list);
listType.initialize(myObject);
}

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: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
at com.sample.listtype.ListType.getListType(ListType.java:26)
at com.sample.listtype.ListType.initialize(ListType.java:21)
at com.sample.listtype.ListType.main(ListType.java:15)


If i declare the list variable with a specific type in MyObject class,



private List<Integer> list;


I'm getting proper result. But how to get the type if I'm setting at run time?






Aucun commentaire:

Enregistrer un commentaire