Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

android - Java how to handle "Unchecked cast" for Array<MyItem> from Object

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.

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

"Unchecked cast for java.lang.Object to 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());

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...