传递null时选择哪个构造函数? [英] Which constructor is chosen when passing null?
问题描述
在下面的示例中,我有2个构造函数:一个接受一个String,一个接受一个自定义对象。在这个自定义对象上存在一个返回String的方法getId()。
In the following example, I have 2 constructors: one that takes a String and one that takes a custom object. On this custom object a method "getId()" exists which returns a String.
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构造函数被选中,但我不知道这是否总是这种情况,为什么。
If I pass null to the constructor, which constructor is chosen and why? In my test the String constructor is chosen, but I do not know if this will always be the case and why.
我希望有人能提供一些洞察
I hope that someone can provide me some insight on this.
提前感谢。
推荐答案
/ p>
By doing this:
ConstructorTest test = new ConstructorTest(null);
编译器会抱怨说:
构造函数ConstructorTest(AnObject)
是不明确的。
The constructor ConstructorTest(AnObject) is ambiguous.
JVM不能选择哪个构造函数invoke,因为它不包含与构造函数匹配的参数类型的信息(请参阅: 15.12.2.5选择最具体的方法)。
The JVM cannot choose which constructor to invoke as it doesn't information of the argument type that matches the constructor (See: 15.12.2.5 Choosing the Most Specific Method).
您可以调用通过类型转换参数,例如:
You can call specific constructor by typecasting the parameter, like:
ConstructorTest test = new ConstructorTest((String)null);
或
ConstructorTest test = new ConstructorTest((AnObject)null);
更新:感谢@OneWorld,在写入时)可以访问此处。
Update: Thanks to @OneWorld, the relevant (up to date link at the time of writing) can be accessed here.
这篇关于传递null时选择哪个构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!