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!");
}
});
}
}
It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class.
Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.
A local inner class consists of a class declared within a method, whereas an anonymous class is declared when an instance is created. So the anonymous class is created on the fly or during program execution.
Yes, you can instantiate a private inner class with Java reflection. To do that, you need to have an instance of outer class and invoke the inner class constructor which will use outer class instance in its first argument. @popgalop Inner classes are the same as methods.
For getting the enclosing class of t
try t.getClass().getEnclosingClass()
. Note that this would return null
if 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$0
variable). 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$0
approach is undocumented and might be compiler dependent. Thus please don't rely on that in production or critical code.
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