Java how to handle “Unchecked cast” for Array from Object

后端 未结 3 1232
陌清茗
陌清茗 2020-12-19 17:22

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.<

相关标签:
3条回答
  • 2020-12-19 18:04

    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.

    Update:

    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());
    
    0 讨论(0)
  • 2020-12-19 18:04

    You can cast your object to ArrayList. you can't cast it to your type

    0 讨论(0)
  • 2020-12-19 18:18

    You can't avoid the warning, but you can hide it with a @SuppressWarnings annotation. Try this:

    new SuperCoolAsyncTask() {
          @Override
          @SuppressWarnings("unchecked")
          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());
    

    The other option, if you're really worried about type safety, is to leave the generic unspecified (i.e. only cast to ArrayList, not ArrayList, and then cast each element as you remove it.

    0 讨论(0)
提交回复
热议问题