私有接口方法的方法参考 [英] Method reference to private interface method

查看:188
本文介绍了私有接口方法的方法参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

public class A {
    public static void main(String[] args) {
        Runnable test1 = ((I)(new I() {}))::test;  // compiles OK
        Runnable test2 = ((new I() {}))::test;     // won't compile 
    }

    interface I {
        private void test() {}
    }
}

我真的不明白......我明白 test()方法私有。但是,如果我们将匿名类强制转换为接口((I)(new I(){})),会有什么变化?更准确地说,我希望看到一个允许该技巧的特定JLS点。

I don't really get the point... I understand that test() method is private. But what is changed if we cast an anonymous class to its interface ((I)(new I() {}))? More precisely I would like to see a particular JLS point which allows that trick.

PS 我已将其报告为编译器的错误(ID :9052217)。在我看来, Runnable test2 =((new I(){})):: test; 应该在这种特殊情况下编译好。

P.S. I have reported it as a bug of compiler (ID : 9052217). It seems to me that Runnable test2 = ((new I() {}))::test; should be compiled fine in this particular case.

PPS 到目前为止,根据我的报告创建了一个错误: https://bugs.openjdk.java.net/browse/JDK-8194998 。它可能会被关闭为无法修复或无论如何。

P.P.S. So far there was created a bug based on my report: https://bugs.openjdk.java.net/browse/JDK-8194998 . It might be that it will be closed as "won't fix" or whatsever.

推荐答案

这不是一个新问题,并且与私有接口方法或方法引用无关。

This is not a new issue, and has nothing to do with private interface methods or method references.

如果更改代码以扩展类而不是实现接口,并调用方法而不是引用它,你仍然得到完全相同的问题。

If you change code to extend a class instead of implement an interface, and to call the method instead of referencing it, you still get exact same problem.

class A {
    public static void main(String[] args) {
        ((I)(new I() {})).test();  // compiles OK
        ((new I() {})).test();     // won't compile 
    }

    class I {
        private void test() {}
    }
}

但是,该代码可以应用于较旧的Java版本,我尝试了Java 9,8,7,6,5和1.4 。所有行为都相同!!

However, that code can be applied to older Java versions, and I tried Java 9, 8, 7, 6, 5, and 1.4. All behave the same!!

问题是私有方法不是继承的 1 ,所以匿名类没有这个方法,一点都不由于私有方法甚至不存在于匿名类中,因此无法调用它。

The issue is that private methods are not inherited1, so the anonymous class doesn't have the method, at all. Since the private method doesn't even exist in the anonymous class, it cannot be called.

当您转换为时我,现在该方法存在供编译器查看,并且由于 I 是一个内部类,因此您被授予访问权限(通过合成方法),即使它是私有的。

When you cast to I, the method now exists for the compiler to see, and since I is an inner class, you are granted access (through a synthetic method), even though it is private.

在我看来,这不是一个错误。这是私有方法在继承环境中的工作方式。

In my opinion, it is not a bug. It's how private methods work in context of inheritance.

1)as 由Jorn Vernee发现 JLS 6.6-5 [私有类成员]不是由子类继承的

1) As found by Jorn Vernee in JLS 6.6-5: "[A private class member] is not inherited by subclasses".

这篇关于私有接口方法的方法参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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