问题描述
在我的Android项目中,我创建了一个抽象的AsyncTask类,我在其中输入了URL,如果需要,则可以分页信息,因此我不需要继续编写HTTP内容等。
In my Android project I have made an abstract AsyncTask class in which I input the URL and if needed paging information so I don't need to keep writing the HTTP stuff etc.
我做了一个抽象方法onAsyncTaskResult(Object o),它必须在使用时实现。
但是当把它投射到适当的对象(可以是不同类型)时,IDE会给我一个警告
I've made an abstract method, onAsyncTaskResult(Object o) which must be implemented on use.However when casting it to the appropriate object (can be of different types) the IDE gives me a warning
未经检查的强制转换为java.lang.Object到java.util.ArrayList< com.company.package.subpackage.MyItem>
这是我的代码片段实现所述函数
Here is my code snippet of the implemention of said function
new SuperCoolAsyncTask() {
@Override
protected void onAsyncTaskResult(Object o) {
if(o instanceof ArrayList) {
//generates warning in the following line
AppConstants.scoreStatistics = (ArrayList<MyItem>)o;
}
}
}.execute(get_url_score_statistics());
我应该如何将其转换为 ArrayList< MyItem>
没有产生警告?
How am i supposed to cast this to an ArrayList<MyItem>
without generating a warning?
如果没有< MyItem>
声明,它会抛出未选中赋值
Without the <MyItem>
declaration it throws an "Unchecked assignment"
推荐答案
如果没有警告,你就无法做到。您正在将 Object
转换为其他类,即使 Object
是 ArrayList 你不知道它的泛型类型。
You cannot do it without a warning. You are casting an Object
to some other class, and even if the Object
is an instance of ArrayList
you don't know it's generic type.
更新:
如果您自己写了 SuperCoolAsyncTask
,您可以使用泛型对类进行参数化:
if you wrote SuperCoolAsyncTask
yourself, you could parametrize the class with generics:
public abstract class SuperCoolAsyncTask<ResultType> {
protected abstract void onAsyncTaskResult(ResultType o);
}
然后,当你调用代码时:
And then, when you invoke your code:
new SuperCoolAsyncTask<ArrayList<MyItem>>() {
@Override
protected void onAsyncTaskResult(ArrayList<MyItem> o) {
AppConstants.scoreStatistics = o;
}
}.execute(get_url_score_statistics());
这篇关于Java如何处理“Unchecked cast” for Array< MyItem>来自Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!