Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

spring boot - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...