传递null时选择哪个构造函数?

7 java null constructor

在下面的示例中,我有2个构造函数:一个使用String,另一个使用自定义对象.在此自定义对象上,存在一个返回String的方法"getId()".

public class ConstructorTest {
 private String property;

 public ConstructorTest(AnObject property) {
  this.property = property.getId();
 }

 public ConstructorTest(String property) {
  this.property = property;
 }

 public String getQueryString() {
  return "IN_FOLDER('" + property + "')";
 }
}
Run Code Online (Sandbox Code Playgroud)

如果我将null传递给构造函数,选择哪个构造函数,为什么?在我的测试中,选择了String构造函数,但我不知道是否总是这样,为什么.

我希望有人可以为我提供一些见解.

提前致谢.

Buh*_*ndi 15

通过做这个:

ConstructorTest test = new ConstructorTest(null);
Run Code Online (Sandbox Code Playgroud)

编译器会抱怨说:

构造函数ConstructorTest(AnObject)不明确.

JVM无法选择要调用的构造函数,因为它无法识别与构造函数匹配的类型(请参阅:15.12.2.5选择最具体的方法).

您可以通过类型化参数来调用特定的构造函数,例如:

ConstructorTest test = new ConstructorTest((String)null);
Run Code Online (Sandbox Code Playgroud)

要么

ConstructorTest test = new ConstructorTest((AnObject)null);
Run Code Online (Sandbox Code Playgroud)

更新:感谢@OneWorld,可以在此处访问相关链接(撰写本文时的最新信息).