Peter Keefe
Peter Keefe

Reputation: 1135

Unchecked cast warning

I am getting an Unchecked Cast warning and despite looking through many StackOverflow posts, cannot seem to solve this. What is the correct, safe way to make this cast? Thanks in advance :-)

/**
 * Fragment for retaining data across screen orientation changes
 */

public class RetainedFragment<T> extends Fragment {

    public T data;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    public static <T> RetainedFragment<T> findOrCreate(FragmentManager fm, String tag) {

        // THIS LINE I GET AN UNCHECKED CAST WARNING 
        RetainedFragment<T> retainFragment = (RetainedFragment<T>) fm.findFragmentByTag(tag); 

        if(retainFragment == null){
            retainFragment = new RetainedFragment<>();
            fm.beginTransaction()
                    .add(retainFragment, tag)
                    .commitAllowingStateLoss();
        }

        return retainFragment;
    }
}

Upvotes: 0

Views: 395

Answers (1)

Ben P.
Ben P.

Reputation: 54204

This comes down to exactly how generics were implemented in Java. The short story is that there's no way to know at runtime whether your RetainedFragment is actually a RetainedFragment<T>. In other words, the system knows that it's a RetainedFragment, but it can't know that T data is the type you want.

You can read more here: https://docs.oracle.com/javase/tutorial/java/generics/genTypes.html

Upvotes: 1

Related Questions