2 回答

TA貢獻1794條經驗 獲得超7個贊
好的,我想我在 T 和 ? 之間感到困惑,所以我找到了一種無警告的方法:
public Downloader getDownloader(Context context, Integer... positions) throws Exception {
Class<? extends Downloader> mClass = getDownloaderClassName();
Downloader downloader = mClass.cast(mClass.getConstructors()[0].newInstance(context));
if (downloader != null)
downloader.setPositions(positions);
return downloader;
}
public abstract Class<? extends Downloader> getDownloaderClassName();
然后,抽象方法就變成了:
@Override
public Class<? extends Downloader> getDownloaderClassName() {
return DemoDownloader.class;
}
在后代。
我想當我需要特定的字段或方法時,我只需要轉換 getDownloader 的結果。

TA貢獻1817條經驗 獲得超6個贊
簽名public <T extends Downloader> T getDownloader(Context context, Integer... positions)
不是類型安全的。它創建getDownloader
了一個通用方法,這意味著無論調用者想要什么,它都必須正常工作T
,而不知道是T
什么。請注意,T
不會出現在任何參數類型中。這意味著具有相同確切參數的相同確切調用必須以某種方式返回類型Downloader1
,如果這是一個調用者想要的,并且Downloader2
如果這是另一個調用者想要的,則還必須返回類型,而該getDownloader
方法沒有關于調用者想要什么的任何信息!這顯然是不可能的,除非getDownloader
總是返回null
。
簽名public Downloader getDownloader(Context context, Integer... positions)
不同,因為它表示該getDownloader
方法返回 type Downloader
。您的getDownloader
方法選擇要返回的事物的類型(只要它是 的子類型Downloader
);調用者不選擇類型,并且不能對返回的事物做出任何假設,除非它是Downloader
. 那是類型安全的。
添加回答
舉報