简体   繁体   中英

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;
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM