结合了Java中的CRTP私人领域的使用私人的访问似乎在可见性规则痒痒一个奇怪的边缘情况:与自我约束的仿制药
public abstract class Test<O extends Test<O>> implements Cloneable {
private int x = 0;
@SuppressWarnings("unchecked")
@Override
protected final O clone() {
try {
return (O) super.clone();
} catch (CloneNotSupportedException ex) {
throw new AssertionError(ex);
}
}
public final int getX() {
return x;
}
public final O withX(int x) {
O created = clone();
created.x = x; // Compiler error: The field Test<O>.x is not visible
return created;
}
}
简单地改变withX()
方法来此...
public final O withX(int x) {
O created = clone();
Test<O> temp = created;
temp.x = x;
return created;
}
...使代码编译。我在Oracle的javac
和Eclipse的编译器中对此进行了测试。是什么赋予了?
可克隆和克隆是用Java中的WTF和陷阱填充的。 – Powerlord
@Powerlord正如下面接受的答案中所记录的,这个问题与'clone()'无关。 –