我有一個問題來獲取列表的類型。問題是聲明我沒有指定類型。我只在運行時設置它。泛型 - 獲取引用類型
我有一個POJO類
public class MyObject<T> {
private String name;
private List<T> list;
//getter and setter
}
我按照this SO question,並試圖我下面的代碼
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);
}
}
然後我得到以下異常
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)
如何獲得類型如果我在運行時設置?
*但是,如何獲取類型,如果我設置在運行時?* List在運行時沒有類型([erasure](http://docs.oracle.com/javase/tutorial/java/generics/erasure.html)),所以這個問題並沒有什麼意義。最好告訴我們你真正想要做什麼。 – Radiodef