Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference anonymous object from within a nested anonymous class

Is it possible to do something like this (I use initializer blocks to shorten the example)

new A() {{
  new B() {{
    method(outer.this);
  }}
}}

Where I supply the this of the outer object as a parameter to the method call within the second anonymous class? I cannot use A.this, this gives a compile error.

Note: the given code does not compile, it should only illustrate what I'm trying to achieve.

Edit: example that lies closer to the actual use case:

public class Outer {

  public SomeBean createBean() {
    return new SomeBean() {

      private final Object reference = new SomeClass() {

        @Override
        public void notify() {
          Outer.callback(/*what goes here???*/);
        }
      };

      //Methods...
    };
  }

  public static void callback(final SomeBean bean) {
    // do stuff with bean
  }
}

And the compile error I get is just that I'm not providing the correct argument to callback, as I don't know how to reference the SomeBean subclass...

like image 472
Ozymandias Avatar asked Jan 23 '26 12:01

Ozymandias


2 Answers

If you really must, I guess this should work.

new A() {
    {
        new B() {{
            method();
        }};
    }
    private void method() {
        method(this);
    }
}

(Historical note: With -target 1.3 or earlier, this should NPE.)

If you don't need the exact type of the A inner class.

new A() {
    {
        new B() {{
            method(a);
        }};
    }
    private A a() {
        return this;
    }
}
like image 185
Tom Hawtin - tackline Avatar answered Jan 26 '26 02:01

Tom Hawtin - tackline


@TomHawtin 's answer is good, mine is quite similar. I would do this:

new A() {
    private final A anon = this;
    /*init*/ {
        new B() {
            /*init*/ {
                method(anon);
            }
        }
    }
}

This will probably give you slightly better performance than calling a method to get your A instance. The main benefit is IMO this is easier to read/maintain.

Edit: @Tomas 's answer is also very similar, but required that you keep a reference to your new A object in the outer-outer class, where it might not be needed.

In light of op's edit:

public SomeBean createBean() {
    SomeBean myBean = new SomeBean() {
        private final Object reference = new SomeClass() {
            @Override
            public void notify() {
                Outer.callback(/*what goes here???*/);
            }
        };
        //Methods...
    };
    return myBean;
}

FYI obj.notify() is a final method in Object, you can't override it. JavaDoc here

like image 22
Aaron J Lang Avatar answered Jan 26 '26 02:01

Aaron J Lang