簡體   English   中英

返回泛型方法 function 返回泛型自類型無需強制轉換

[英]Generic method to return function returning generic self-type without the need to cast

老實說,我什至不確定這個標題是否有意義。 希望下面的代碼能解釋手頭的問題。

package what.ever.you.like;

import java.util.function.UnaryOperator;

class SelfTypeTemplates {

    public static <SELF extends AbstractSelfType> UnaryOperator<SELF> simpleBound() {
        return self -> self;
    }

    public static <SELF extends AbstractSelfType<SELF>> UnaryOperator<SELF> boundWithGenericType() {
        return self -> self;
    }
}

class ConcreteSelfType extends AbstractSelfType<ConcreteSelfType> {

    public ConcreteSelfType() {
        super(ConcreteSelfType.class);
    }

    public ConcreteSelfType applySimpleBound() {
        // How to get rid of the type cast?
        return (ConcreteSelfType) SelfTypeTemplates.simpleBound().apply(this);
    }

    public ConcreteSelfType applyBoundWithGenericType() {
        // Compile error because `this` is ConcreteSelfType, but required is SELF
        return SelfTypeTemplates.boundWithGenericType().apply(this);
    }
}

class AbstractSelfType<SELF extends AbstractSelfType<SELF>> {
    protected final SELF myself;

    protected AbstractSelfType(final Class<?> type) {
        this.myself = (SELF) type.cast(this);
    }
}

我的問題是這兩種方法applySimpleBound()applyBoundWithGenericType() 前者編譯得很好,但需要顯式轉換,這是我想擺脫的。 后者不編譯,因為.apply(this)需要類型SELF但提供的是ConcreteSelfType

所以我的問題是,如何在SelfTypeTemplates中指定方法的簽名以返回UnaryOperator<SELF>以便調用返回的 function ( .apply(this) )不需要在客戶端代碼中強制轉換(即ContreteSelfType )?

嘗試在泛型和返回類型中使用不同的界限。 還沒有找到沒有類型轉換的工作版本。

有時編譯器出於某種原因無法推斷出正確的類型。 要解決此問題,您可以這樣指定它:

class ConcreteSelfType extends AbstractSelfType<ConcreteSelfType> {

    public ConcreteSelfType() {
        super(ConcreteSelfType.class);
    }

    public ConcreteSelfType applySimpleBound() {
        // How to get rid of the type cast?
        return SelfTypeTemplates.<ConcreteSelfType>simpleBound().apply(this);
    }

    public ConcreteSelfType applyBoundWithGenericType() {
        // Compile error because `this` is ConcreteSelfType, but required is SELF
        return SelfTypeTemplates.<ConcreteSelfType>boundWithGenericType().apply(this);
    }
}

這兩個選項都以這種方式編譯,您不需要強制轉換。

暫無
暫無

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

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