How to have Java method return generic list of any type?

后端 未结 8 1964
逝去的感伤
逝去的感伤 2020-11-28 07:13

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

List

        
相关标签:
8条回答
  • 2020-11-28 07:27

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

    `

    0 讨论(0)
  • 2020-11-28 07:29

    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;
    }
    
    0 讨论(0)
提交回复
热议问题