Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing inner anonymous class members

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

like image 817
Saravanan M Avatar asked Nov 26 '08 04:11

Saravanan M


1 Answers

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);
like image 164
Tom Hawtin - tackline Avatar answered Oct 05 '22 19:10

Tom Hawtin - tackline