5

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!");
            }
        });
    }
}
Qiang Li
  • 10,593
  • 21
  • 77
  • 148
  • Seems to be a duplicate of http://stackoverflow.com/questions/471749/can-i-discover-a-java-class-declared-inner-classes-using-reflection – Dexygen Jan 26 '12 at 20:33
  • Do you need the class only or the actual instance of the enclosing class? – Thomas Jan 26 '12 at 20:34

2 Answers2

8

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.

Community
  • 1
  • 1
Thomas
  • 87,414
  • 12
  • 119
  • 157
  • I am sure that you've noted here I am also out of the outer class! – Qiang Li Jan 26 '12 at 20:42
  • @QiangLi that shouldn't matter, the method that retrieves the outer instance in the question I linked just happens to be in the outer class but doesn't have to be. – Thomas Jan 26 '12 at 20:44
  • OK. Can you then complete the example to access the outer class instance from within the method `A.foo`? – Qiang Li Jan 26 '12 at 20:45
  • @QiangLi what about trying it yourself? Basically just copy the method you find in the accepted answer of that link. – Thomas Jan 26 '12 at 20:47
0

You can do this to see if t is an inner class of B:

public static void foo(Thread t) {
    System.out.println(t.getClass().getName().contains("B$"));
    // OR
    System.out.println(t.getClass().getEnclosingClass().equals(B.class));
}
Garrett Hall
  • 29,524
  • 10
  • 61
  • 76