我收到未经检查的Cast警告,尽管浏览了许多StackOverflow帖子,但似乎无法解决此问题。进行此投射的正确,安全的方法是什么?提前致谢 :-)

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

最佳答案

这完全取决于Java中泛型的实现方式。简短的故事是,无法在运行时知道RetainedFragment是否实际上是RetainedFragment<T>。换句话说,系统知道它是RetainedFragment,但不能知道T data是您想要的类型。

您可以在此处阅读更多信息:https://docs.oracle.com/javase/tutorial/java/generics/genTypes.html

09-30 15:34