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

在下面的示例中,我有两个构造函数:一个接受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 + "')"; } } 

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

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

提前致谢。

通过做这个:

 ConstructorTest test = new ConstructorTest(null); 

编译器会抱怨说:

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

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

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

 ConstructorTest test = new ConstructorTest((String)null); 

要么

 ConstructorTest test = new ConstructorTest((AnObject)null); 

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

编译器将生成错误。

Java使用它可以根据参数找到的最具体的构造函数。
PS:如果添加构造函数(InputStream),编译器会因为模糊而抛出错误 – 它无法知道更具体的内容:String或InputStream,因为它们位于不同的类层次结构中。