gpt4 book ai didi

java - 用正确的返回类型覆盖通用的 getter

转载 作者:行者123 更新时间:2023-12-04 10:01:09 25 4
gpt4 key购买 nike

我在尝试制作一个小型系统时遇到了 Java 泛型的问题。

public void bar(){
final Shape shape = new Shape();
final Painter<Shape> shapePainter = shape.getPainter();

final Circle circle = new Circle();
final Painter<Circle> circlePainter = circle.getPainter();
}

class Shape {

public Painter<? extends Shape> getPainter(){
return new Painter<>(this);
}

}

class Circle extends Shape {

@Override
public Painter<Circle> getPainter(){
return new CirclePainter(this);
}

}

class Painter<E extends Shape> {

public Painter(final E element){
// ...
}

public void paint(final E shape){
// ...
}

}

class CirclePainter extends Painter<Circle> {

public CirclePainter(final Circle element){
super(element);
}

@Override
public void paint(final Circle shape){
// ...
}
}

编译失败,第 3 行(final Painter<Shape> shapePainter = shape.getPainter();)出现错误:

Incompatible types:

Required: Bar.Painter < org.example.Bar.Shape>

Found: Bar.Painter < capture< ? extends org.example.Bar.Shape>>

这可以通过将故障线路更改为:

final Painter<?> shapePainter = shape.getPainter();

但是,后续调用如下:

shapePainter.paint(shape);

会抛出另一个异常:

paint (capture< ? extends org.example.Bar.Shape>) in Painter cannot be applied

to (org.example.Bar.Shape)


我觉得我遗漏了 Java 泛型的一些简单部分,它们可以帮助解决这个问题。我试过摆弄 Shape#getPainter 的返回类型, 但这通常会在 Circle#getPainter 中留下编译器错误或在 bar似乎没有任何可能的解决方案。

如果使用泛型无法做到这一点,还有哪些其他解决方案可用?

最佳答案

您需要使用 CRTP 使整个类通用:

class Shape<T extends Shape<T> {

public Painter<T> getPainter(){
return new Painter<>(this);
}

}
class Painter<E extends Shape<E>> { ... }

关于java - 用正确的返回类型覆盖通用的 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com