简体   繁体   English

延迟加载类本身的事件顺序

[英]Order of events lazy loading the class itself

If I have this Java class, what exactly is the order of events upon construction/initialization? 如果我有这个Java类,构造/初始化时事件的顺序到底是什么?

class Start {

private Start s = new Start();

public Start(){} //constructor

}

when I call new Start() , isn't there some circular logic being invoked? 当我调用new Start() ,是否没有调用某些循环逻辑?

Yes, you got yourself a StackOverflowError here, since creating an instance of Start causes another isntance to be created when the s member is initialized, which creates another instance and so on. 是的,您在这里遇到了StackOverflowError,因为创建Start的实例会导致在初始化s成员时创建另一个实例,从而创建另一个实例,依此类推。

private Start s = new Start();

public Start(){}

behaves as : 表现为:

private Start s;

public Start() {s = new Start();}

To avoid such infinite constructor calls, you can pass an instance of Start to the constructor, or you can initialize the s member by some other method : 为了避免这种无限的构造函数调用,可以将Start的实例传递给构造函数,或者可以通过其他方法初始化s成员:

private Start s;

public Start(Start s) {this.s = s;}

or 要么

private Start s;

public Start() {}

public initS () {s = new Start();}

A way to lazy set a field is to use a getter. 延迟设置字段的一种方法是使用吸气剂。 eg 例如

class Start {
    private Start nested = null;

    public Start getNested() {
        return nested == null ? nested = new Start() : nested;
    }
}

This is not thread safe, but avoids infinite loops if used carefully. 这不是线程安全的,但如果谨慎使用,则可以避免无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM