如何获得泛型方法参数的类型参数类? [英] How to get type arguments class of generic method parameter?
本文介绍了如何获得泛型方法参数的类型参数类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何获取传递给方法的参数的类型参数?例如,我有
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.
这篇关于如何获得泛型方法参数的类型参数类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文