如何获得泛型方法参数的类型参数类?
问题描述:
如何获取传递给方法的参数的类型参数?例如,我有
How to get the type argument of an argument passed to a method ? For example I have
List<Person> list = new ArrayList<Person>();
public class Datastore {
public <T> void insert(List<T> tList) {
// when I pass the previous list to this method I want to get Person.class ;
}
}
答
由于类型擦除,唯一的方法是将类型作为参数传递给方法.
Due to type erasure, the only way you can do it is if you pass the type as an argument to the method.
如果您有权访问数据存储区代码并可以修改,则可以尝试执行以下操作:
If you have access to the Datastore code and can modify you can try to do this:
public class Datastore {
public T void insert(List<T> tList, Class<T> objectClass) {
}
}
然后调用它
List<Person> pList = new ArrayList<Person>();
...
dataStore.insert(pList, Person.class);
我对这种类型的问题的每次回答都是将类作为参数发送给方法.
Every response I've seen to this type of question was to send the class as a parameter to the method.