0

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;
    }
}
Peter Keefe
  • 1,095
  • 14
  • 22
  • I tried that: Fragment fragment = fm.findFragmentByTag(tag); if (fragment instanceof RetainedFragment) { RetainedFragment retainFragment = (RetainedFragment) fragment; } But it still give the same warning. – Peter Keefe Jul 21 '17 at 15:55
  • [What is SuppressWarnings (“unchecked”) in Java?](https://stackoverflow.com/q/1129795/823393) - but ONLY if you are certain. – OldCurmudgeon Jul 21 '17 at 15:59

1 Answers1

1

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

Ben P.
  • 52,661
  • 6
  • 95
  • 123