关于发布和逸出
public class ThisEscape { public final int id; public final String name; public ThisEscape(EventSource<EventListener> source) { id = 1; source.registerListener(new EventListener() { public void onEvent(Object obj) { System.out.println("id: "+ThisEscape.this.id); System.out.println("name: "+ThisEscape.this.name); } }); name = "xingpc"; } }
二、如何避免this引用逸出 上文演示了由内部类导致的this引用逸出是怎样产生的。它需要满足两个条件:一个是在构造函数中创建内部类(EventListener),另一个是在构造函数中就把这个内部类给发布了出去(source.registerListener)。因此,我们要防止这一类this引用逸出的方法就是避免让这两个条件同时出现。也就是说,如果要在构造函数中创建内部类,那么就不能在构造函数中把他发布了,应该在构造函数外发布,即等构造函数执行完毕,初始化工作已全部完成,再发布内部类。
public class ThisSafe { public final int id; public final String name; private final EventListener listener; private ThisSafe() { id = 1; listener = new EventListener(){ public void onEvent(Object obj) { System.out.println("id: "+ThisSafe.this.id); System.out.println("name: "+ThisSafe.this.name); } }; name = "flysqrlboy"; } public static ThisSafe getInstance(EventSource<EventListener> source) { ThisSafe safe = new ThisSafe(); source.registerListener(safe.listener); return safe; } }
原文:https://www.cnblogs.com/xingpengcheng/p/10526353.html