未经检查的投射警告

时间:2017-07-21 15:53:06

标签: java android

我收到一封未经检查的投射警告,尽管查看了很多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;
    }
}

1 个答案:

答案 0 :(得分:1)

这归结为Java中如何实现泛型。简短的故事是,无法知道在运行时是否RetainedFragment实际上是RetainedFragment<T>。换句话说,系统知道它是RetainedFragment,但它无法知道T data是您想要的类型。

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