Accessing inner anonymous class members

后端 未结 7 1779
灰色年华
灰色年华 2021-01-05 18:00

Is there any way other than using reflection to access the members of a anonymous inner class?

7条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-05 18:08

    You can use local classes instead anonymous class. Look:

    public class Test {
        public static void main(String... args) {
            class MyInner {
                private int value = 10;
            }
    
            MyInner inner = new MyInner();
            System.out.println(inner.value);
        }
    }
    

    You can have reference of MyInner type only in the method body though. So outside of the method you will not be able to use its fields/methods that are not declared in its super class (java.lang.Object in this case) or interface.

提交回复
热议问题