陈宇凡:android Avoid Memory Leaks 内部类问题

来源:百度文库 编辑:九乡新闻网 时间:2024/05/08 03:15:24
An inner class holds a reference to the object instance that created it; thus, in the following: public class Outer {   public class Inner   {   }   Inner i = new Inner(); } 
Outer o = new Outer; Outer.Inner oi = o.i; o = null;   // o is still alive because oi references it oii has a hidden reference (the "outer this") to the enclosing class instance o. So long as somebody holds a reference to the Inner object, the reference to the outer object remains alive. If you mark the enclosing class or enclosing method as static, the inner class will be a static inner class, which holds no reference to the enclosing class (and also therefore lacks the ability to referencere fields and methods of the outer class). Event listeners were a common source of leaks (meaning, longer-lived objects than intended) in Swing code back in the day. Might try hunting around that way on Google--there used to be a great article on "four types of lapsed listeners" back then, that described all of this in more detail.