Java如何处理“未经检查的强制转换"对于 Array<MyItem>从对象 [英] Java how to handle &quot;Unchecked cast&quot; for Array&lt;MyItem&gt; from Object

查看:30
本文介绍了Java如何处理“未经检查的强制转换"对于 Array<MyItem>从对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 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 的强制转换"

这是我实现上述功能的代码片段

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 而不产生警告?

How am i supposed to cast this to an ArrayList<MyItem> without generating a warning?

如果没有 声明,它会抛出未检查的赋值"

Without the <MyItem> declaration it throws an "Unchecked assignment"

推荐答案

没有警告就不能这样做.您正在将 Object 转换为其他类,即使 ObjectArrayList 的实例,您也不知道它是泛型类型.

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如何处理“未经检查的强制转换"对于 Array<MyItem>从对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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