问题描述
我有这个方法
I have this method
public <T> T PostQuery(String url, Object graph, Class<T> returnType)
我想称之为像这样
List<User> users = PostQuery("blabla", SomeObj, List<User>.class);
但是我在最后一个参数上出错。它允许我只写 List.class
,这使得它成为一个字符串列表,而不是我想要的。
But I get error on the last argument. It allows me to only write List.class
, which makes it a list of strings, not what I want.
我该怎么做?
推荐答案
的泛型类型(类型擦除)没有 List< User> .class
只有 List.class
。因此,请使用List.class,或者您可以创建第二个方法,该方法已经返回像这样的列表
Due to Java implementation of generics (type erasure) there is no List<User>.class
only List.class
. So use either use just List.class or you can create a second method that already returns a list like this
public List<T> T PostQueryList(String url, Object graph, Class<T> returnType)
List<User> users = PostQueryList("blabla", SomeObj, User.class);
如果您确实需要访问 List< User>
您可能需要查看Guava的TypeTokens
If you really need access to List<User>
you might want to look into TypeTokens from Guava https://code.google.com/p/guava-libraries/wiki/ReflectionExplained
这篇关于我如何获得类类型的通用列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!