[英]Java - List cast to be able to use addAll function
假設我有一個調用某個方法的實體
Object methodVal = ety.getClass().getMethod("someMethod").invoke(ety);
我的目標是將它轉換為 List 以便使用像addAll
這樣的函數,所以我嘗試了
List.class.cast(methodVal).addAll((Collection<?>) Objects.requireNonNull(someValue));
//someValue is an Object and I cast it to Collection<?>)
代碼運行良好,應用程序仍然可以運行,但是我收到一條警告說
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 ?>
關於如何修復警告/錯誤的任何想法? 謝謝
只需取消有關未檢查分配的警告,並且不要使用原始類型。
要么注釋該方法:
@SuppressWarnings("unchecked")
void myMethod() {
// ... code here ...
((List<Object>) methodVal).addAll((Collection<?>) Objects.requireNonNull(someValue));
// ... code here ...
}
或者分配給一個局部變量並在那里注釋:
@SuppressWarnings("unchecked")
List<Object> list = (List<Object>) methodVal;
list.addAll((Collection<?>) Objects.requireNonNull(someValue));
您可以通過將“methodVal”包裝在一個新的 List 實例中來解決這個問題,這樣您就可以使用 add all。 下面是一些示例代碼:
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.