Accessing inner anonymous class members

后端 未结 7 1945
灰色年华
灰色年华 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:28

    
    public class AccessAnonymous {
        private Runnable runnable; // to have instance of the class
    
        public static void main(String[] args) throws Exception {
            AccessAnonymous a = new AccessAnonymous();
            a.a(); // init field
    
            Class clazz = a.runnable.getClass();
            Field field = clazz.getDeclaredField("i");
            field.setAccessible(true);
    
            int int1 = field.getInt(a.runnable);
            System.out.println("int1=" + int1);
        }
    
        public void a() {
            runnable = new Runnable() {
                private int i = 1;
    
                public void run() {
                    i = 90;
                }
    
            };
            runnable.run();// change value
        }
    }
    

提交回复
热议问题