未经检查的铸件:';java.lang.Class<;捕获<&燃气轮机&燃气轮机';至';java.lang.Class<;T>;
我正在尝试在我的超级类中编写以下方法:未经检查的铸件:';java.lang.Class<;捕获<&燃气轮机&燃气轮机';至';java.lang.Class<;T>;,java,android,generics,Java,Android,Generics,我正在尝试在我的超级类中编写以下方法: public <T extends Downloader> T getDownloader(Context context, Integer... positions) throws Exception { Class<T> mClass = (Class<T>)Class.forName(getDownloaderClassName()); T downloader = mClass.cast(mCl
public <T extends Downloader> T getDownloader(Context context, Integer... positions) throws Exception {
Class<T> mClass = (Class<T>)Class.forName(getDownloaderClassName());
T downloader = mClass.cast(mClass.getConstructors()[0].newInstance(context));
if (downloader != null)
downloader.setPositions(positions);
return downloader;
}
更准确地说,这个超类是抽象的,getDownloaderClassName()实际上定义如下:
public abstract String getDownloaderClassName();
这样子类就可以选择Downloader的子类,它们需要使用getDownloader()检索。好的,我想我把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();
public Downloader getDownloader(上下文、整数…位置)引发异常{
类签名公共T getDownloader(上下文、整数…位置)
不是类型安全的。它使getDownloader
成为一种通用方法,这意味着无论调用方希望T
是什么,它都必须正确工作,而不知道T
是什么。请注意,T
不会出现在任何参数类型中。这意味着使用相同参数的相同精确调用nts必须以某种方式返回typeDownloader1
如果这是一个调用方想要的,并且返回typeDownloader2
如果这是另一个调用方想要的,而getDownloader
方法没有关于调用方想要什么的任何信息!这显然是不可能的,除非getDownloader
总是返回 空
签名public Downloader getDownloader(Context Context,Integer…positions)
不同,因为它表示getDownloader
方法返回类型Downloader
。您的getDownloader
方法选择要返回的对象的类型(只要它是Downloader
的子类型);调用者不选择类型,并且不能对返回的内容进行任何假设,除非它是下载程序的实例。这是类型安全的
(T)mClass.getConstructors....
public abstract String getDownloaderClassName();
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;
}