我的IDE抱怨“NCM_Callable无法转换为此行Callable<ReturnInterface<? extends Object>>
上的this.ph.submitCallable(new NCM_Callable(this, new DeviceGroup(this.deviceGroupNames.get(i)), ph)); In the "fetchDevices()" method
我只是希望能够将Callables传递给我的ecs,它返回一个包含任何类型对象的ReturnInterface。
我怀疑使用&lt;&gt;时出现了问题通用定义,但我似乎无法弄清楚它是什么。任何帮助,将不胜感激。
@Override
public void fetchDevices() throws Exception {
System.out.println("[NCM_Fetcher]fetchingDevices()");
for (int i = 0; i < this.deviceGroupNames.size(); i++) {
System.out.println("[NCM_Fetcher]fetchingDevices().submitting DeviceGroup Callable " + i+ " of "+this.deviceGroupNames.size());
this.ph.submitCallable(new NCM_Callable(this, new DeviceGroup(this.deviceGroupNames.get(i)), ph));
}
this.ph.execute();//See progressBarhelper below
}
ProgressBarHelper:我在“ecs.submit()”中遇到一个奇怪的错误。从我的阅读,似乎我可能需要一个辅助方法?我该如何解决?
public class ProgressBarHelper extends SwingWorker<Void, ReturnInterface> implements ActionListener {
ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
protected CompletionService<ReturnInterface<?>> ecs;
public final void submitCallable(Callable<? extends ReturnInterface<?>> c) {
//create a map for this future
ecs.submit(c);
this.callables.add(c);//Error here is Callable<CAP#1 cannot be converted to Callable<ReturnInterface<?>>
System.out.println("[ProgressBarHelper]submitted");
}
}
最后,NCM_Callable类及其泛型。
public class NCM_Callable implements Callable<ReturnInterface<ResultSet>>, ReturnInterface<ResultSet> {
答案 0 :(得分:0)
据我所知,有问题的一行是ecs.submit
:
public final void submitCallable(Callable<? extends ReturnInterface<?>> c) {
// create a map for this future
ecs.submit(c); // Error here is Callable<CAP#1 cannot be converted to Callable<ReturnInterface<?>>
this.callables.add(c); // this is fine on my machine
}
问题是java泛型是invariant。有一种解决方法:您可以使用命名,绑定类型替换通配符:
public final <T extends ReturnInterface<?>> void // this is how you name and bind the type
submitCallable(Callable<T> c) { // here you are referring to it
// create a map for this future
ecs.submit((Callable<ReturnInterface<?>>) c); // here you need to cast.
...
}
由于type erasure,投射在运行时是可以的。但是要对那些Callables
。
最后,您可以调用此函数:
private static class ReturnInterfaceImpl implements ReturnInterface<String> {
};
public void foo() {
Callable<ReturnInterfaceImpl> c = new Callable<ReturnInterfaceImpl>() {
@Override
public ReturnInterfaceImpl call() throws Exception {
return null;
}
};
submitCallable(c);
}