Search code examples
javasyntaxinner-classesmember

Can I access new methods in anonymous inner class with some syntax?


Is there any Java syntax to access new methods defined within anonymous inner classes from outer class? I know there can be various workarounds, but I wonder if a special syntax exist?

For example

class Outer {

    ActionListener listener = new ActionListener() {

        @Override
        void actionPerformed(ActionEvent e) { 
             // do something
        }

        // method is public so can be accessible
        public void MyGloriousMethod() {
             // viva!
        }

    };

    public void Caller() {
         listener.MyGloriousMethod(); // does not work!
    }


}

MY OWN SOLUTION

I just moved all methods and members up to outer class.


Solution

  • Once the anonymous class instance has been implicitly cast into the named type it can't be cast back because there is no name for the anonymous type. You can access the additional members of the anonymous inner class through this within the class, in the expression immediate after the expression and the type can be inferred and returned through a method call.

    Object obj = new Object() {
        void fn() {
            System.err.println("fn");
        }
        @Override public String toString() {
            fn();
            return "";
        } 
    };
    obj.toString();
    
    
    
    new Object() {
        void fn() {
            System.err.println("fn");
        }
    }.fn();
    
    
    identity(new Object() {
        void fn() {
            System.err.println("fn");
        }
    }).fn();
    ...
    private static <T> T identity(T value) {
        return value;
    }