Method reference to private interface method

前端 未结 4 1638
长情又很酷
长情又很酷 2021-01-31 04:31

Consider the following code:

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


        
4条回答
  •  我在风中等你
    2021-01-31 05:00

    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() {}
        }
    }
    

    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!!

    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.

    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 found by Jorn Vernee in JLS 6.6-5: "[A private class member] is not inherited by subclasses".

提交回复
热议问题