编程语言
首页 > 编程语言> > java-抽象递归泛型导致绑定不匹配

java-抽象递归泛型导致绑定不匹配

作者:互联网

在尝试以逻辑方式构造类时,我发现Java能够执行递归泛型.几乎正是我在结构上寻找的东西,但是我遇到了抽象类的问题.我认为Foo和Bar在这个示例中会非常混乱,因此我将与我的实际项目相关的类命名为.

public abstract class GeneCarrier<T extends GeneCarrier<T>> {
    protected Gene<T> gene;
    //...
}

public class Gene<T extends GeneCarrier<T>> {
    //...
}

public abstract class Organism extends GeneCarrier<Organism>{
    //...
}

public class Human extends Organism {
    public void foo(){
        Gene<Human> g; // Bound mismatch: The type Human is not a valid substitute for the bounded parameter <T extends GeneCarrier<T>> of the type Gene<T>
    }
}

我以为问题可能出在我的抽象有机体类的定义上,但这也产生了类似的错误:

public abstract class Organism extends GeneCarrier<? extends Organism>{
    //...
}

尝试将抽象类与递归模板定义一起使用时是否存在固有的问题,还是我在类定义中犯了一个错误?

解决方法:

Is there an inherent problem in trying to use an abstract class with recursive template definitions, or have I made a mistake in the class definitions?

看来您做错了.基因的类型参数T的递归界限必须使人的类型参数应该意味着人是GeneCarrier< Human>.但这不是-人类是基因载体.

为了正确实现此模式,应将递归类型参数沿继承树传播,直到到达我喜欢的“叶子”类为止,在这种情况下,该类似乎是Human:

public abstract class Organism<T extends Organism<T>> extends GeneCarrier<T> {
    //...
}

public final class Human extends Organism<Human> {
    public void foo(){
        Gene<Human> g; // valid
    }
}

这可以解决当前的问题,但是您应该了解在Java(通常称为Curiously Recurring Template Pattern)中使用“自我类型”的经历.我在这篇文章中详细介绍了如何实现此模式及其陷阱:Is there a way to refer to the current type with a type variable?

总的来说,我发现开发人员会尝试使用“自我类型”来在某些类上实现类型安全的“复制”方法(由于您的类型名称与基因相关,因此在这里似乎是这种情况).当发生这种情况时,我总是建议尝试将复制责任分离为单独的类型,以避免递归泛型的复杂性.例如My answer here.

标签:abstract-class,generics,java
来源: https://codeday.me/bug/20191122/2056028.html