简体   繁体   English

如何获取泛型方法参数的类型参数类?

[英]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) {
    }
}

and then call it by doing然后通过做调用它

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.我看到的对此类问题的每个响应都是将类作为参数发送给方法。

Due to Type Erasure I doubt whether we can get it, barring some reflection magic which might be able to do it.由于类型擦除,我怀疑我们是否能得到它,除非有一些反射魔法可以做到。

But if there are elements inside the list, we can reach out to them and invoke getClass on them.但是如果列表中有元素,我们可以联系它们并在它们上调用 getClass。

I think you can't do that.我认为你不能那样做。 Check out this class:看看这个类:

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();
    }
}

You can get the type parameters from a class or a field but it is not working for generic methods.您可以从类或字段中获取类型参数,但它不适用于泛型方法。 Try using a non-generic method!尝试使用非泛型方法!

OR或者

another solution might be passing the actual Class object to the method.另一种解决方案可能是将实际的Class对象传递给该方法。

You can try this ...你可以试试这个...

if(tList != null && tList.size() > 0){
    Class c = tList.get(0).getClass();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM