Java - List cast to be able to use addAll function

点点圈 提交于 2020-01-07 09:31:34

问题


Supposed I have an entity that invokes some method

Object methodVal = ety.getClass().getMethod("someMethod").invoke(ety);

My goal is to cast it to List in order to user the function like addAll, so I tried

List.class.cast(methodVal).addAll((Collection<?>) Objects.requireNonNull(someValue)); 

//someValue is an Object and I cast it to Collection<?>)

The code is working fine and the app is still can run, however I'm getting a warning saying

Unchecked call to 'addAll(Collection<? extends E>)' as a member of raw type 'java.util.List'

and also I tried

((List<?>) methodVal).addAll((Collection<?>) Objects.requireNonNull(someValue));

however I'm getting an error saying

Required type: Collection <? extends capture of ?>
Provided: Collection <capture of ?>

Any idea on how can I fix the warning / error? Thanks


回答1:


Just suppress the warning about unchecked assignment, and don't use raw types.

Either annotate the method:

@SuppressWarnings("unchecked")
void myMethod() {
    // ... code here ...

    ((List<Object>) methodVal).addAll((Collection<?>) Objects.requireNonNull(someValue));

    // ... code here ...
}

Or assign to a local variable and annotate there:

@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) methodVal;

list.addAll((Collection<?>) Objects.requireNonNull(someValue));



回答2:


You can solve this by wrapping the "methodVal" in a new List instance so you can use add all. Here is some example code:

public class Main {


    public static void main(String[] args) throws Exception {
        Test a = new Test();

        Object result = Test.class.getMethod("get").invoke(a);

        List<Object> list = new ArrayList<>((Collection<?>) result);

        list.addAll(List.of(7, 8, 9));

        System.out.println(list);
    }


    static class Test {

        public List<Integer> get() {
            return List.of(1, 2, 3, 4, 5);
        }
    }
}


来源:https://stackoverflow.com/questions/59241734/java-list-cast-to-be-able-to-use-addall-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!