在Java中,每当创建内部类实例时,它都会与外部类的实例相关联。出于好奇,是否可以将内部类与外部类的另一个实例相关联?
是的,这是可能的,尽管这对我来说听起来是一个非常糟糕的主意。这个想法是设置否则final
使用反射指向外部实例的指针(不保证成功)。
import java.lang.reflect.*;
public class Me {
final String name;
Me(String name) {
this.name = name;
}
class InnerMe {
String whoAreYou() {
return name;
}
}
InnerMe innerSelf() {
return new InnerMe();
}
public static void main(String args[]) throws Exception {
final Me me = new Me("Just the old me!");
final InnerMe innerMe = me.innerSelf();
System.out.println(innerMe.whoAreYou()); // "Just the old me!"
Field outerThis = innerMe.getClass().getDeclaredFields()[0];
outerThis.setAccessible(true);
outerThis.set(innerMe, new Me("New and improved me!"));
System.out.println(innerMe.whoAreYou()); // "New and improved me!"
}
}
这里的关键部分是outerThis.setAccessible(true);
-- a 安全管理器 http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html可以执行一项政策来阻止这种情况的成功。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)