[英]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 以便使用像
addAll
这样的函数,所以我尝试了
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.您可以通过将“methodVal”包装在一个新的 List 实例中来解决这个问题,这样您就可以使用 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.