是否可以使用同一类的另一个构造函数的方法结果调用构造函数?
我希望能够接受多种形式的输入,例如:
public class MyClass
{
public MyClass(int intInput)
{
...
}
public MyClass(String stringInput);
{
this(convertToInt(stringInput));
}
public int convertToInt(String aString)
{
return anInt;
}
}
当我尝试编译它时,我得到了
error: cannot reference this before supertype constructor has been called
引用convertToInt
。
最佳答案
您只需要将convertToInt
设置为静态即可。由于它并不真正依赖类实例中的任何内容,因此它可能并不真正属于此类。
这是一个例子:
class MyClass {
public MyClass(String string) {
this(ComplicatedTypeConverter.fromString(string));
}
public MyClass(ComplicatedType myType) {
this.myType = myType;
}
}
class ComplicatedTypeConverter {
public static ComplicatedType fromString(String string) {
return something;
}
}
您必须这样做,因为在幕后, super 构造函数(在本例中为 Object)需要在您自己的构造函数运行之前被调用。通过在对 super();
的不可见调用之前引用 this
(通过方法调用),您违反了语言限制。
参见 the JLS第 8.8.7 节和 more of the JLS第 12.5 节。
关于构造函数链中的 Java 方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505387/