我有一些这样的代码:
public class Foo {
private int x;
public Foo() {
}
public Foo(int x) {
try {
//do some initialisation stuff like:
this.x = x;
}
catch(Exception ge){
//call empty constructor not possible
//this();
//this.EMPTY();
//Foo();
}
}
public static final Foo EMPTY = new Foo();
}
我想知道是否有可能实现这样的事情(我知道调用另一个构造函数必须是构造函数中的第一条语句)。 我在 SO 上四处查看,但没有找到任何类似的东西,这让我相信也许我应该在实例化方法中处理错误逻辑。
最佳答案
只需更改执行顺序:
public class Foo {
Integer i;
public Foo() {
System.out.println("Empty constructor invoked");
}
public Foo(Integer i) {
this(); //can be omitted
try {
System.out.println("i initialized to : "+i.toString());
} catch (Exception ex) {
System.out.println("i NOT initialized ");
}
}
public static void main(String[] args) {
new Foo(); //prints: Empty constructor invoked
new Foo(5);//prints: Empty constructor invoked
//prints: i initialized to : 5
new Foo(null);//prints: Empty constructor invoked
//prints: i NOT initialized
}
}
关于java - 如何从另一个调用一个空的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44745859/