简体   繁体   中英

How do I get class type of generic list?

I have this method

public <T> T PostQuery(String url, Object graph, Class<T> returnType)

and I want to call it like this

List<User> users = PostQuery("blabla", SomeObj, List<User>.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.

How can I do that?

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

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

仅使用User.class作为参数

According to this: https://stackoverflow.com/a/2226038/1264582 there is a workaround. Just use a subclass of your generic class.

Use public <T> T PostQuery(String url, Object graph){} would be ok,because you have declared a generic type to this method when declare <T> like:

public <T> T PostQuery(String url, Object graph){
    Object obj = null;
    //...
    return (T)obj;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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