How to have Java method return generic list of any

2020-01-25 06:16发布

I would like to write a method that would return a java.util.List of any type without the need to typecast anything:

List<User> users = magicalListGetter(User.class);

List<Vehicle> vehicles = magicalListGetter(Vehicle.class);

List<String> strings = magicalListGetter(String.class);

What would the method signature look like? Something like this, perhaps(?):

public List<<?> ?> magicalListGetter(Class<?> clazz) {
    List<?> list = doMagicalVooDooHere();

    return list;
}

Thanks in advance!

8条回答
混吃等死
2楼-- · 2020-01-25 07:03

Let us have List<Object> objectList which we want to cast to List<T>

public <T> List<T> list(Class<T> c, List<Object> objectList){        
    List<T> list = new ArrayList<>();       
    for (Object o : objectList){
        T t = c.cast(o);
        list.add(t);
    }
    return list;
}
查看更多
【Aperson】
3楼-- · 2020-01-25 07:04

Another option is doing the following:

public class UserList extends List<User>{

}

public <T> T magicalListGetter(Class<T> clazz) {
    List<?> list = doMagicalVooDooHere();
    return (T)list;
}

List<User> users = magicalListGetter(UserList.class);

`

查看更多
登录 后发表回答