簡體   English   中英

將通用返回類型轉換為接口類型

[英]Casting generic return type to interface type

我正在嘗試為通用包裝器創建工廠方法,但遇到的問題是我要么需要傳遞所需的返回類型(wrapTyped()-方法),要么必須將輸入參數顯式轉換為所需的返回類型( wrapAuto()方法,第一次使用)。 但是我很懶 ,不想寫多余的演員:)

有什么方法可以表達wrapAuto()的聲明,以便案例“ wantThis”(在最底部)起作用?

public class GenericFactory {

static class Wrapper<T> {
    T wrappdObject;
    boolean flag;
    String name;

    public Wrapper(T wrappedObject, boolean flag, String name) {
        this.wrappdObject = wrappedObject;
        this.flag = flag;
        this.name = name;
    }

    public T getObject() {
        return wrappdObject;
    }

    // some more irrelevant methods
}

static interface InterfaceType {
}

static class ImplementationA implements InterfaceType {
}

static <U> Wrapper<U> wrapTyped(Class<U> type, U wrappedObject, boolean flag, String name) { 
    return new Wrapper<U>(wrappedObject, flag, name);
}

static <U> Wrapper<U> wrapAuto(U wrappedObject, boolean flag, String name) {
    return new Wrapper<U>(wrappedObject, flag, "NoName");
}

// compiles, but is cumbersome
public Wrapper<InterfaceType> cumbersome = wrapTyped(InterfaceType.class, new ImplementationA(), true, "A");

// compiles, but is also cumbersome
public Wrapper<InterfaceType> alsoUgly = wrapAuto((InterfaceType) new ImplementationA(), true, "B");

// Want this, but "Type mismatch error"
public Wrapper<InterfaceType> wantThis = wrapAuto(new ImplementationA(), false, "C");

}

我將其簡化了一些,為簡單起見,我只聲明了一組接口和具體實現。 我練習包裝器類可用於許多完全不同的,不相關的類型。

在您的方法wrapAuto ,添加另一個類型參數,以U為上限,並將其用作形式參數類型:

static <U, T extends U> Wrapper<U> wrapAuto(T wrappedObject, boolean flag, String name) {
    return new Wrapper<U>(wrappedObject, flag, "NoName");
}

然后這將工作:

Wrapper<InterfaceType> wantThis = wrapAuto(new ImplementationA(), false, "C");

通過此調用,將T推斷為ImplementationA ,將U推斷為InterfaceType T extends U的邊界與這些類型完全匹配。


參考文獻:

您編寫的方法沒有任何問題。 但是推斷並不完美。 您始終可以顯式指定類型參數:

public Wrapper<InterfaceType> wantThis = GenericFactory.<InterfaceType>wrapAuto(new ImplementationA(), false, "C");

暫無
暫無

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

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