Accessing inner anonymous class members

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

    Anonymous inner classes have a type but no name.

    You can access fields not defined by the named supertype. However once assigned to a named type variable, the interface is lost.

    Obviously, you can access the fields from within the inner class itself. One way of adding code is through an instance initialiser:

    final AtomicInteger y = new AtomicInteger();
    new Runnable() {
        int x;
        {
            x = 5;
            doRun(this);
            y.set(x);
        }
        public void run() {
            ... blah ...
        }
    };
    

    The value returned by the anonymous inner class expression has the anonymous type, so you have one chance to use it outside of the class itself:

    final int y = new Runnable() {
        int x;
        {
            x = 5;
            doRun(this);
        }
        public void run() {
            ... blah ...
        }
    }.x;
    

    You can also pass it through a method declared similar to:

     T doRun(T runnable);
    

提交回复
热议问题