Reputation: 301
public class OuterClass {
public class InnerClass{
void test(){
};
}
}
class Client{
public void x(){}
public void lucian() {
OuterClass.InnerClass innerClass = new OuterClass().new InnerClass(){
void test() {
Client.this.x();
x();
******** // how can I get the reference of the OuterClass at here? ********
}
};
innerClass.test();
}
}
I know the compiler will produce a constructor for the anonymous Inner Class with two arguments,one is the Client's refrence, another one is the OuterClass, but how can I get the OuterClass's refrence like Client's refrence in methoud test() using Client.this? Not the Client.this!! But the OuterClass's refrence in Client.
Upvotes: 3
Views: 68
Reputation: 891
You can save reference to the object of OuterClass (so far you create it anonymously):
class Client{
private OuterClass outerClass;
public OuterClass getOuterClass() {
return outerClass;
}
public void setOuterClass(OuterClass outerClass) {
this.outerClass = outerClass;
}
public void x(){
System.out.println("===");
}
public void lucian() {
OuterClass outerClass = new OuterClass();
setOuterClass(outerClass);
OuterClass.InnerClass innerClass = outerClass.new InnerClass(){
void test() {
Client1.this.x();
x();
System.out.println(getOuterClass());
}
};
innerClass.test();
}
public static void main(String[] args) {
Client client = new Client();
client.lucian();
}
}
Upvotes: 1
Reputation: 102923
You can't. Not with crazy reflection shenanigans, anyway. So, just write it out:
public void lucian() {
OuterClass oc = new OuterClass();
OuterClass.InnerClass ic = oc.new InnerClass() {
void test() {
Client.this.x();
x();
oc.x();
}
};
ic.test();
}
NB: Non-static inner classes are weird and rarely correct. Beginner java coders should never use them; advanced java coders should think long and hard. In any case, your default choice for inner classes should always be that they are static.
Upvotes: 1