簡體   English   中英

Java泛型導致問題

[英]Java Generics Causing Problems

我的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。

我懷疑使用<>泛型定義有問題,但我似乎無法弄清楚它是什么。 任何幫助,將不勝感激。

  @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> {

據我ecs.submit ,有問題的行是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泛型是不變的 有一個解決方法:您可以使用命名的綁定類型替換通配符:

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. 
    ...
}

由於類型擦除,在運行時鑄件是可以的。 但是要對那些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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM