对Object.clone()的功能引用不会编译 [英] Functional reference to Object.clone() doesn't compile

查看:134
本文介绍了对Object.clone()的功能引用不会编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译

  import java .util.concurrent.Callable; 

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

使用Oracle JDK提供:

  Main.java:6:错误:不兼容类型:无效方法引用
可调用<?> x = super :: clone;
^
clone()在Object

中具有受保护的访问权限因为类应该能够访问其父的受保护方法。这个表达式在Eclipse的编译器中工作良好。



此外,()这是一个错误吗?

h2_lin>解决方案

super 实际上不是一个表达式,没有静态类型。 super.foo()具有与 this.foo()相同的访问权限;这就是说,方法调用在字节代码中以不同的方式翻译为超级调用,而不是正常调用。



JLS在此不是​​很清楚;例如在受保护的访问部分中, a>,未提及 super.protectedMember 表单;但显然这种形式应该在JLS中讨论;它应该是可访问的。 (该部分确实建议 X :: m Xm 应该被视为相同的wrt访问权限)



方法参考,措辞也是模糊的;但是, super :: clone 应该可以访问 super.clone() >

已创建一个错误报告: JDK- 8139836:当x受保护时不能使用super :: x方法引用。它的当前状态是它将在Java 9中修复。


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?

解决方案

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.

这篇关于对Object.clone()的功能引用不会编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆