简体   繁体   中英

Java - List cast to be able to use addAll function

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM