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

后端 未结 8 2016
逝去的感伤
逝去的感伤 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:16

    private Object actuallyT;
    
    public  List magicalListGetter(Class klazz) {
        List list = new ArrayList<>();
        list.add(klazz.cast(actuallyT));
        try {
            list.add(klazz.getConstructor().newInstance()); // If default constructor
        } ...
        return list;
    }
    

    One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()).

提交回复
热议问题