如何获取传递给方法的参数的类型参数?例如我有
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 ;
}
}
由于类型擦除,唯一的方法是将类型作为参数传递给方法。
如果您有权访问数据存储区代码并且可以进行修改,则可以尝试这样做:
public class Datastore {
public T void insert(List<T> tList, Class<T> objectClass) {
}
}
然后通过做调用它
List<Person> pList = new ArrayList<Person>();
...
dataStore.insert(pList, Person.class);
我看到的对此类问题的每个响应都是将类作为参数发送给方法。
由于类型擦除,我怀疑我们是否能得到它,除非有一些反射魔法可以做到。
但是如果列表中有元素,我们可以联系它们并在它们上调用 getClass。
我认为你不能那样做。看看这个类:
public class TestClass
{
private List<Integer> list = new ArrayList<Integer>();
/**
* @param args
* @throws NoSuchFieldException
* @throws SecurityException
*/
public static void main(String[] args)
{
try
{
new TestClass().getClass().getDeclaredField("list").getGenericType(); // this is the type parameter passed to List
}
catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NoSuchFieldException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
new TestClass().<Integer> insert(new ArrayList<Integer>());
}
public <T> void insert(List<T> tList)
{
ParameterizedType paramType;
paramType = (ParameterizedType) tList.getClass().getGenericInterfaces()[0];
paramType.getActualTypeArguments()[0].getClass();
}
}
您可以从类或字段中获取类型参数,但它不适用于泛型方法。尝试使用非泛型方法!
或者
另一种解决方案可能是将实际Class
对象传递给方法。
你可以试试这个...
if(tList != null && tList.size() > 0){
Class c = tList.get(0).getClass();
}