結合了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()'無關。 –