Java如何处理来自Object的Array <MyItem>的"Unchecked cast"

Rae*_*Rae 4 java android warnings casting arraylist

在我的Android项目中,我创建了一个抽象的AsyncTask类,我在其中输入了URL,如果需要,还可以分页信息,因此我不需要继续编写HTTP内容等.

我已经创建了一个抽象方法onAsyncTaskResult(Object o),它必须在使用时实现.但是,当将其转换为适当的对象(可以是不同类型)时,IDE会向我发出警告

"Unchecked cast for java.lang.Object to java.util.ArrayList<com.company.package.subpackage.MyItem>"

这是我执行所述函数的代码片段

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());
Run Code Online (Sandbox Code Playgroud)

如何在ArrayList<MyItem>不产生警告的情况下将其投射到一个?

没有<MyItem>声明它会抛出"未经检查的任务"

dar*_*jan 5

没有警告就不能这样做.你正在Object向其他类投射,即使你Object是一个实例,ArrayList也不知道它是泛型类型.

更新:

如果你SuperCoolAsyncTask自己写的,你可以用泛型参数化这个类:

public abstract class SuperCoolAsyncTask<ResultType> {

    protected abstract void onAsyncTaskResult(ResultType o);

}
Run Code Online (Sandbox Code Playgroud)

然后,当您调用代码时:

new SuperCoolAsyncTask<ArrayList<MyItem>>() {
    @Override
    protected void onAsyncTaskResult(ArrayList<MyItem> o) {
            AppConstants.scoreStatistics = o;
    }
}.execute(get_url_score_statistics());
Run Code Online (Sandbox Code Playgroud)