DiddiZ
DiddiZ

Reputation: 655

Access anonymous outer class without storing in variable?

Is there a way to access an anonymous outer class? A normal class can be accessed by ClassName.this. This doesn't work, as an anonymous class obviously doesn't have a name. I also tried using the extended class/interface (like Runnable.this) but it doesn't seem like it would work this way.

I'm sure this may be not the best coding style, I'm just curious if it's possible without storing this of the outer in a variable.

Example, watch out for outer.this:

public class A
{
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (outher.this) {
                            outher.this.notify();
                        }
                    }
                }).start();
                try {
                    synchronized (this) {
                        wait();
                    }
                } catch (final InterruptedException ex) {}
            }
        }).start();
    }
}

Upvotes: 3

Views: 526

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

You could add a method to return this middle this. It would be in scope but not hidden (is that the right term? Shadowed? I forget.).

public static void main(String[] args) {
    new Thread(new Runnable() {
        Runnable middleThis() { return this; } // <-- this
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (middleThis()) {
                        middleThis().notify();

Note, although anonymous inner classes have no name, they still are types. So adding members is visible to the immediate expression (new X() { Y z; }.z) and inside. You can't do middleThis().middleThis().

Upvotes: 1

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

No, there is no way to access anonymous classes from anywhere, except from inside them (i.e. otherwise than by this reference). Or by an explicitly declared variable.

final Runnable r1 = new Runnable() {...};
Runnable r2 = new Runnable() {
    public void run() {
         synchronized(r1) {...}
    }
};

Upvotes: 2

Related Questions