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

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

    You can simply cast to List and then check if every element can be casted to T.

    public  List asList(final Class clazz) {
        List values = (List) this.value;
        values.forEach(clazz::cast);
        return values;
    }
    

提交回复
热议问题