java 泛型方法返回函数,该函数返回泛型自类型而无需强制转换

zdwk9cvp  于 2023-01-19  发布在  Java
关注(0)|答案(1)|浏览(142)

老实说,我甚至不确定这个标题是否有意义,希望下面的代码能解释这个问题。

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>,以便调用返回的函数(.apply(this)),不需要在客户端代码(即ContreteSelfType)中强制转换
尝试在泛型和返回类型中使用不同的界限。尚未找到没有类型转换的工作版本。

dojqjjoe

dojqjjoe1#

有时候编译器无法推断出正确的类型。要解决这个问题,您可以如下指定:

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);
    }
}

这两个选项都以这种方式编译,并且不需要强制转换。

相关问题