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...
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;
}
}
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With