从内部类对象获取外部类对象我有以下代码。我想获得创建内部类对象的外部类对象。inner..我该怎么做?public class OuterClass {
public class InnerClass {
private String name = "Peakit";
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
InnerClass inner = outer.new InnerClass();
// How to get the same outer object which created the inner object back?
OuterClass anotherOuter = ?? ;
if(anotherOuter == outer) {
System.out.println("Was able to reach out to the outer object via inner !!");
} else {
System.out.println("No luck :-( ");
}
}}编辑:好吧,你们中的一些人建议通过添加一个方法来修改内部类:public OuterClass outer() {
return OuterClass.this;}但是,如果我没有修改内部类的控制,那么(仅仅是确认)我们有其他方法从内部类对象获取对应的外部类对象吗?
3 回答
红颜莎娜
TA贡献1842条经验 获得超12个赞
慕后森
TA贡献1802条经验 获得超5个赞
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); }}
添加回答
举报
0/150
提交
取消