代码之家  ›  专栏  ›  技术社区  ›  qichuan

在这种情况下,“this”引用是否会从构造函数转义?

  •  2
  • qichuan  · 技术社区  · 15 年前

    我知道,由于线程安全问题,“this”引用不应在构造函数中转义,因为该对象尚未完全构造,但已“泄漏”给其他对象。例如

    public class TestClass{
           public TestClass(){
                StaticClass.addListener(this);
           }
    }
    

    public class TestClass{
           public TestClass(){
    
           }
           public TestClass(String str){
                this();
                StaticClass.addListener(this);
           }
    }
    
    1 回复  |  直到 15 年前
        1
  •  7
  •   L. Cornelius Dol    15 年前

    总之,是的,你的 this

    TestClass obj=new TestClass();
    StaticClass.addListener(obj);
    

    StaticClass.addListener(new TestClass());