Are all final variables captured by anonymous classes?

后端 未结 4 1238
北恋
北恋 2021-02-13 00:03

I thought I knew the answer to this, but I can\'t find any confirmation after an hour or so of searching.

In this code:

public class Outer {

    // othe         


        
4条回答
  •  无人及你
    2021-02-13 00:37

    I was curious and surprised by your statement that much (why would compiler do such thing???), that I had to check it myself. So I made simple example like this

    public class test {
        private static Object holder;
    
        private void method1() {
            final Object obj1 = new Object();
            final Object obj2 = new Object();
            holder = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println(obj1);
                }
            };
        }
    }
    

    And resulted with following bytecode for of method1

     private method1()V
       L0
        LINENUMBER 8 L0
        NEW java/lang/Object
        DUP
        INVOKESPECIAL java/lang/Object. ()V
        ASTORE 1
       L1
        LINENUMBER 9 L1
        NEW java/lang/Object
        DUP
        INVOKESPECIAL java/lang/Object. ()V
        ASTORE 2
       L2
        LINENUMBER 10 L2
        NEW test$1
        DUP
        ALOAD 0
        ALOAD 1
        INVOKESPECIAL test$1. (Ltest;Ljava/lang/Object;)V
        PUTSTATIC test.holder : Ljava/lang/Object;
    

    Which means:

    • L0 - store first final with idx 1 (ASTORE 1)
    • L1 - store second final with idx 2(that one is not used in anon class) (ASTORE 2)
    • L2 - create new test$1 with argumets (ALOAD 0) this and obj1 (ALOAD 1)

    So I have no idea, how did you get to the conclusion that obj2 is passed to anonymous class instance, but it was simply wrong. IDK if it is compiler dependent, but as for what other has stated, it is not impossible.

提交回复
热议问题