Not sure if I am asking a sound question. I know every inner class keeps a reference to the enclosing class object. So can I reference the enclosing class object outside that enclosing class given the anonymous inner class as function parameter?
class A{
public static void foo(Thread t) {
//here, how to get the reference of the enclosing class object of "t",
//i.e. the object of class B. I know, somebody might have put in a
//non-inner class Thread. But how can I check if "t" is really from an
//anonymous inner class of class B and then do something here?
}
}
class B{
public void bar() {
A.foo(
new Thread() {
public void run() {
System.out.println("inside bar!");
}
});
}
}
For getting the enclosing class of
ttryt.getClass().getEnclosingClass(). Note that this would returnnullif there was no enclosing class.Getting the correct instance of the enclosing class is not that easy, since this would rely on some
undocumented implementation details (namely the
this$0variable). Here’s some more information: In Java, how do I access the outer class when I'm not in the inner class?Edit: I’d like to reemphasize that the
this$0approach is undocumented and might be compiler dependent. Thus please don’t rely on that in production or critical code.