Java - 列表强制转换以能够使用 addAll 函数 [英] Java - List cast to be able to use addAll function

查看:21
本文介绍了Java - 列表强制转换以能够使用 addAll 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个调用某个方法的实体

Supposed I have an entity that invokes some method

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

我的目标是将其转换为 List 以便使用 addAll 之类的功能,所以我尝试了

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'

我也试过了

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

但是我收到一个错误说

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.

或者注释方法:

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

这篇关于Java - 列表强制转换以能够使用 addAll 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆