私有访问与自我限制的泛型

Aar*_*erg 3 java generics visibility

将私有字段访问与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;
    }
}
Run Code Online (Sandbox Code Playgroud)

只需将withX()方法更改为此...

    public final O withX(int x) {
        O created = clone();
        Test<O> temp = created;
        temp.x = x;
        return created;
    }
Run Code Online (Sandbox Code Playgroud)

...使代码编译.我在Oracle javac和Eclipse的编译器中对此进行了测试.是什么赋予了?

Phi*_* JF 7

这实际上不是泛型的问题.该JLS继承规则不断被子类可见私人领域.因为X是私有的,所以它不是类型的成员O,即使它是类型的成员Test<O>并且O是其子类型Test<O>.如果您使用过以下代码:

public final O withX(int x) {
    Test<O> created = clone();
    created.x = x;
    return (O) created;
}
Run Code Online (Sandbox Code Playgroud)

它会工作.这是Java不支持LSP的实例,但它只是类型系统的本地问题,因为私有字段仅可用于相同类型的对象.如果它不起作用,那么私有字段就不会私有.我不认为对递归模板的规则有一个特殊的例外是一个好主意.

请注意,这实际上并不限制您可以做的事情.您可以随时将子类型转换为超类型,以便进行更改,就像在替代代码中一样.