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

标签 java constructor null

在下面的示例中,我有 2 个构造函数:一个接受字符串,另一个接受自定义对象。在这个自定义对象上存在一个返回字符串的方法“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);

编译器会提示说:

The constructor ConstructorTest(AnObject) is ambiguous.

JVM 无法选择调用哪个构造函数,因为它无法识别与构造函数匹配的类型(参见:15.12.2.5 Choosing the Most Specific Method)。

您可以通过对参数进行类型转换来调用特定构造函数,例如:

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

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

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

关于java - 传递 null 时选择哪个构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4021733/

相关文章:

java - 泛型编译问题 : incompatible types

java - Hbase列族设计重要性

java - 如果在类级别设置了 Include.NON_NULL,则 Jackson 序列化 NULL 属性值

c++ - 将枚举传递给构造函数

c++ - "Define"类构造函数中的成员函数

objective-c - 带有 NULL 指针的 CGRectDivide

php - 如何将实际的 NULL 值插入到可为空的列中?

java - SQLite (JDBC) 不写入数据

actionscript-3 - ActionScript 3 构造函数参数问题

iphone - 将合成(保留)属性设置为 nil 时的 EXC_BAD_ACCESS