1、匿名内部类没有被引用的话,匿名内部类的对象用完的话就有回收的机会。
2、如果内部类只是在外部类中引用,当外部类不再引用时,外部类和内部类可以通过gc回收。
内部类引用被外部类以外的其他类引用时,内部类和外部类不能被gc回收,即使外部类不被引用,内部类也有指向外部类的引用)。
实例
public class classouter { object object = new object() { public void finalize() { system.out.println(inner free the occupied memory...); } }; public void finalize() { system.out.println(outer free the occupied memory...); }} public class testinnerclass { public static void main(string[] args) { try { test(); } catch (interruptedexception e) { e.printstacktrace(); } } private static void test() throws interruptedexception { system.out.println(start of program.); classouter outer = new classouter(); object object = outer.object; outer = null; system.out.println(execute gc); system.gc(); thread.sleep(3000); system.out.println(end of program.); }}
以上就是java内部类内存泄漏的原因是什么?的详细内容。
