我试图让以下代码工作但没有成功
protected BackgroundTask<?> backgroundTask = null;
...
protected <T> void confirmBackgroundAction(final BackgroundTask<T> task, final T arg) {
backgroundTask = task;
backgroundTask.attach(AbstractWorkerActivity.this);
backgroundTask.execute(arg);
}
捕获类如下所示:
public abstract class BackgroundTask<T> extends AsyncTask<T, Void, Long> {
...
}
使用此代码,我遇到以下编译错误:
The method execute(capture#26-of ?...) in the type AsyncTask<capture#26-of ?,Void,Long> is not applicable for the arguments (T)
如果我更换
backgroundTask.execute(arg);
与
((BackgroundTask<T>)backgroundTask).execute(arg);
我不再有任何编译错误,但在运行时出现 ClassCastException。 有没有办法将BackgroundTask的实例+参数传递给我的函数?
编辑:我忘记了调用confirmBackgroundAction()方法的代码...
confirmBackgroundAction(new SpecificBackgroundTask(), (Void) null);
SpecificBackgroundTask 的外观
public class SpecificBackgroundTask extends BackgroundTask<Void> {
...
}
最佳答案
在编译时,T
在BackgroundTask<T>
未知,并且最多(理论上)可以存储多种可能类型中的 1 个类型 T,您可以使用这些类型调用 confirmBackgroundAction()
。
编译器无法一致地解决这个问题。改变T
进入interface
您的定义将解决歧义。
关于Java:泛型捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9645761/