Home >Java >javaTutorial >How Can I Access the Outer Class from an Inner Class in Java?
In the provided code snippet, you have nested classes OuterClass and InnerClass. You aim to access the parent class (OuterClass) from an instance of the inner class (InnerClass) without modifying the inner class's code.
Within the InnerClass, you can use the expression OuterClass.this to refer to the enclosing instance of OuterClass. This expression qualifies the this keyword to indicate the enclosing instance. Here's a modified version of your code:
public class OuterClass { public class InnerClass { private String name = "Peakit"; public OuterClass outer() { return OuterClass.this; } } public static void main(String[] args) { OuterClass outer = new OuterClass(); InnerClass inner = outer.new InnerClass(); OuterClass anotherOuter = inner.outer(); if(anotherOuter == outer) { System.out.println("Was able to reach out to the outer object via inner !!"); } else { System.out.println("No luck :-( "); } } }
When you run this code, the outer() method in InnerClass returns the enclosing instance of OuterClass, which you can then compare with the original OuterClass instance.
Through experimentation, it has been found that the field holding the reference to the outer class has package-level access. This means you can technically access the outer class through reflection:
Field field = InnerClass.class.getDeclaredField("this"); field.setAccessible(true); OuterClass outer = (OuterClass) field.get(inner);
Note: This approach is discouraged by the Java Language Specification and may not be reliable across different Java versions.
The above is the detailed content of How Can I Access the Outer Class from an Inner Class in Java?. For more information, please follow other related articles on the PHP Chinese website!