DecadeAnkle / JavaStudyRecord

Java学习内容汇总
0 stars 0 forks source link

this引用逸出 #3

Open DecadeAnkle opened 1 year ago

DecadeAnkle commented 1 year ago

逸出示例


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 = "hahahaha";

  }

ThisEscape在构造函数中引入了一个内部类EventListener,而内部类会自动的持有其外部类(这里是ThisEscape)的this引用。 source.registerListener会将内部类发布出去,从而ThisEscape.this引用也随着内部类被发布了出去。但此时ThisEscape对象还没有构造完成 —— id已被赋值为1,但 name还没被赋值,仍然为null

> [this引用逸出](https://blog.csdn.net/flysqrlboy/article/details/10607295)