我的IDE抱怨“此行Callable<ReturnInterface<? extends Object>>上的NCM_Callable无法转换为this.ph.submitCallable(new NCM_Callable(this, new DeviceGroup(this.deviceGroupNames.get(i)), ph)); In the "fetchDevices()" method我只希望能够将Callables传递给我的ecs,该ecs返回包含任何对象类型的ReturnInterface。我怀疑泛型定义的使用存在问题,但是我似乎无法弄清楚它是什么。任何帮助,将不胜感激。 @Overridepublic 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> { (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 据我检查,有问题的行是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);} (adsbygoogle = window.adsbygoogle || []).push({});
07-24 13:16