对原始类型成员的未选中调用

2022-09-02 19:12:41
Android Studio 2.1.2

我有这个警告,我似乎找不到原因。我没有使用任何原始类型。

Unchecked call to attachView(DownloadViewContract) as a member of raw type

我有以下界面

public interface DownloadPresenterContract {
    interface Operations<DownloadViewContract> {
        void attachView(DownloadViewContract view);
        void detachView();
        void getData();
    }
}

以及以下实现

public class DownloadPresenterImp implements
        DownloadPresenterContract.Operations<DownloadViewContract> {

    private DownloadViewContract mView;

    private DownloadPresenterImp() {
    }

    public static DownloadPresenterImp getNewInstance() {
        return new DownloadPresenterImp();
    }

    /* Operations */
    @Override
    public void attachView(DownloadViewContract view) {
        mView = view;
    }
}

这是我的视图界面

public interface DownloadViewContract {
    void onSuccessDownload();
    void onFailureDownload(String errMsg);
}

在我的片段中,这是我的观点

public class DownloadView extends Fragment implements DownloadViewContract {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        mDownloadPresenterContract = DownloadPresenterImp.getNewInstance();

        /* UNCHECKED MEMBER TO RAW TYPE */
        mDownloadPresenterContract.attachView(DownloadView.this);
    }
    .....
}

我不明白为什么我会收到警告,因为我在演示器界面中显式命名了类型。由于我的观点实现了接口,我认为应该没有任何问题。DownloadViewContractDownloadViewContract

非常感谢您的任何建议,


答案 1

为什么会出现这种行为?

原始类型是没有任何参数的泛型类型。例如,和 是泛型类型,而 是原始类型。您可以混合使用原始类型和泛型类型,但如果编译器无法判断语句或表达式是否类型安全,编译器将发出警告。ArrayList<String>ArrayList<MyObject>ArrayList

    ArrayList myList;
    myList = new ArrayList();
    myList.add("abc"); // “unchecked call to add(E) as a member of the raw type java.util.ArrayList
    Integer s = (Integer) myList.get(0);

考虑上面的代码,其中 myList 的类型是原始类型。在调用 myList.add 时会发出警告,因为无法确定 myList 中允许使用哪种类型的元素。警告是:“未选中对 add(E) 作为原始类型 java.util.ArrayList 成员的调用”。第五行没有警告,但很明显,由于 myList.get(0) 不是整数,因此在运行时将引发类强制转换异常。

有关更多详细信息,请参阅此处


答案 2

我相信您在没有指定类型的情况下声明了mDownloadPresenterContract,而是像这样声明它:

DownloadPresenterContract.Operations<DownloadViewContract> mDownloadPresenterContract = DownloadPresenterImp.getNewInstance();

mDownloadPresenterContract.attachView(DownloadView.this);

推荐