Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 955
Suzan Cioc Avatar asked May 29 '12 13:05

Suzan Cioc


People also ask

Can anonymous class have multiple methods?

You can't. The only way to be able to call multiple methods is to assign the anonymous class instance to some variable. However, in your LinkedList sub-class example you can only assign the anonymous class instance to a LinkedList variable, which will only allow you to call methods of the LinkedList class.

How do you access methods in an inner class?

As the inner class exists inside the outer class we must instantiate the outer class in order to instantiate the inner class. Hence, to access the inner class, first create an object of the outer class after that create an object of the inner class.

Can an anonymous inner class implement multiple interfaces?

A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.

Can an anonymous inner class contain static methods?

Anonymous classes also have the same restrictions as local classes with respect to their members: You cannot declare static initializers or member interfaces in an anonymous class. An anonymous class can have static members provided that they are constant variables.


1 Answers

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;
}
like image 117
Tom Hawtin - tackline Avatar answered Oct 11 '22 10:10

Tom Hawtin - tackline