Functional reference to Object.clone() doesn't

2020-03-08 08:40发布

问题:

Compiling

import java.util.concurrent.Callable;

class Ideone
{
    Callable<?> x = super::clone;
}

using Oracle JDK gives:

Main.java:6: error: incompatible types: invalid method reference
    Callable<?> x = super::clone;
                    ^
    clone() has protected access in Object

which makes no sense as a class should be able to access its parent's protected methods. This expression works fine in Eclipse's compiler.

Also, () -> super.clone() compiles fine....

Is this a bug?

回答1:

super is not actually an expression, and there's no static type to talk about. super.foo() has the same access as this.foo(); it's just that, the method invocation is translated differently in byte code, as "super invoke", as opposed to "normal invoke".

JLS is not very clear on this; e.g. in section of protected access, the super.protectedMember form is not mentioned; but obviously that form should be discussed in JLS; and it should be accessible. (The section does suggest that X::m and X.m should be treated the same w.r.t. access right)

In the section of method reference, the wording is also vague; nevertheless, super::clone should be accessible the same ways as super.clone() is accessible.

A bug report has been created: JDK-8139836: “Can't use super::x method reference when x is protected”. Its current status is that it will be fixed in Java 9.