3

I know i can get the instance of the enclosing class using:

OuterClass.this

But i can do it only within the inner class code itself. only I have is reference of the Inner class instance withing another class code. How can i get the OuterClass instance through the inner class instance?

Shelef
  • 3,707
  • 6
  • 23
  • 28
  • While it might be possible to actually do that (interesting question!), you should probably reconsider your design (or post a reasonable example where such access is really needed) – Lukas Eder Mar 06 '13 at 16:51
  • 1
    Here is a good answer to this question: http://stackoverflow.com/questions/1816458/getting-hold-of-the-outer-class-object-from-the-inner-class-object – tdedecko Mar 06 '13 at 17:01

2 Answers2

3

You can define a getter that returns OuterClass to callers from the outside:

public class InnerClass {
    ...
    public OuterClass getOuterInstance() {
        return OuterClass.this;
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

You could (but you shouldn't) use reflection for the job:

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

    public static void main(String[] args) throws Exception {

        // Create the inner instance
        Inner inner = new Outer().new Inner();

        // Get the implicit reference from the inner to the outer instance
        // ... make it accessible, as it has default visibility
        Field field = Inner.class.getDeclaredField("this$0");
        field.setAccessible(true);

        // Dereference and cast it
        Outer outer = (Outer) field.get(inner);
        System.out.println(outer);
    }
}

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509