Search code examples
javaanonymous-class

Accessing inner anonymous class members


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


Solution

  • 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 extends Runnable> T doRun(T runnable);