Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the enclosing class object from anonymous inner class as function parameter

Tags:

java

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!");
            }
        });
    }
}
like image 960
Qiang Li Avatar asked Jan 26 '12 20:01

Qiang Li


People also ask

Is an anonymous class an inner class?

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.

How do you access the inner class of an outer 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.

What is the difference between anonymous class and inner class?

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.

How do you access private inner class with reflection?

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.


1 Answers

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.

like image 56
Thomas Avatar answered Oct 12 '22 22:10

Thomas