当我将匿名内部类传递给函数时,我可以从该类的方法中引用当前范围内的变量,如下所示:
class Caller {
private Object callerPrivate;
// ...
public void someMethod() {
final String callerLocal = "Eyes only";
ISomeInterface anon = new ISomeInterface() {
public void doSomethingInterfacy {
System.out.println(callerPrivate.toString());
System.out.println(callerLocal);
}
};
// this is some other object that puts ISomeInterfaces in a queue
// and makes them doSomethingInterfacy later
myCallManager.enqueue(anon);
}
}
现在,在上面的 someMethod 运行之后,调用者和带有小匿名的队列可以分道扬镳,据我了解,JVM 保持所有引用正常,因此这始终有效。
但是,如果,例如,队列被序列化,程序关闭并重新启动,然后队列被反序列化并且其中的项目应该运行,而 Caller 实例早已消失并被遗忘,该怎么办?
还有其他方法可以让周围的对象和匿名内部类以一种在匿名类内部调用不再起作用的方式分离吗?