我正在阅读有关子类化生成器类的this文章。我理解了这篇文章,但有一个小细节让我感到困扰。这里有一个方法,
public static Builder<?> builder() {
return new Builder2();
}
当我将
Builder<?>
更改为原始类型Builder
时,编译器无法编译代码。错误是:Rectangle.java:33: error: cannot find symbol
System.out.println(Rectangle.builder().opacity(0.5).height(250);
使用额外的
<?>
向编译器传递了什么额外的信息?我怀疑编译器在编译期间无法找到正确的实例。如果我在(A)中删除注释标记,代码就可以编译和运行。一直引用Rectangle实例。所以,我猜测是编译器失败了。如果有人能指向一篇解释这个问题或带领我找到更多信息的文章,那就太好了。谢谢。
我在这里粘贴了代码:
public class Shape {
private final double opacity;
public static class Builder<T extends Builder<T>> {
private double opacity;
public T opacity(double opacity) {
this.opacity = opacity;
return self();
}
/* Remove comment markers to make compilation works (A)
public T height(double height) {
System.out.println("height not set");
return self();
}
*/
protected T self() {
System.out.println("shape.self -> " + this);
return (T) this;
}
public Shape build() {
return new Shape(this);
}
}
public static Builder<?> builder() {
return new Builder();
}
protected Shape(Builder builder) {
this.opacity = builder.opacity;
}
}
public class Rectangle extends Shape {
private final double height;
public static class Builder<T extends Builder<T>> extends Shape.Builder<T> {
private double height;
public T height(double height) {
System.out.println("height is set");
this.height = height;
return self();
}
public Rectangle build() {
return new Rectangle(this);
}
}
public static Builder<?> builder() {
return new Builder();
}
protected Rectangle(Builder builder) {
super(builder);
this.height = builder.height;
}
public static void main(String[] args) {
Rectangle r = Rectangle.builder().opacity(0.5).height(250).build();
}
}
(T) this
不安全。 - newacct