有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

导致问题的Java泛型

我的IDE抱怨“NCM_Callable无法转换为这一行上的Callable<ReturnInterface<? extends Object>>

我只是希望能够将可调用项传递给我的ecs,ecs返回一个包含任何类型对象的ReturnInterface

我怀疑我使用<&燃气轮机;一般定义,但我似乎不知道它是什么。任何帮助都将不胜感激

  @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_可调用类及其泛型

public class NCM_Callable implements Callable<ReturnInterface<ResultSet>>, ReturnInterface<ResultSet> {

共 (1) 个答案

  1. # 1 楼答案

    据我所知,有问题的行是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);
    }