为什么 `System.out.println(null);` 给出 "The method println(char[]) is ambiguous for the type PrintStream error"?
Why does `System.out.println(null);` give "The method println(char[]) is ambiguous for the type PrintStream error"?
我正在使用代码:
System.out.println(null);
显示错误:
The method println(char[]) is ambiguous for the type PrintStream
为什么 null
不代表 Object
?
PrintStream
中有 3 个 println
方法接受引用类型 - println(char x[])
、println(String x)
、println(Object x)
.
当您通过null
时,所有3个都适用。方法重载规则优先选择具有最具体参数类型的方法,因此未选择 println(Object x)
。
然后编译器无法在前两个之间进行选择 - println(char x[])
和 println(String x)
- 因为 String
并不比 char[]
更具体,反之亦然。
如果要选择特定方法,请将 null 转换为所需类型。
例如:
System.out.println((String)null);
如果您调用 System.println(null)
有多个候选方法(带有 char []
、String
和 Object
参数)并且编译器无法决定采用哪一个.
修复
向 null 添加显式转换。
System.out.println((Object)null);
Why does't null
represent Object?
来自JLS 4.1 The Kinds of Types and Values
There is also a special null type, the type of the expression null,
which has no name.
Because the null type has no name, it is impossible
to declare a variable of the null type or to cast to the null type.
The null reference is the only possible value of an expression of null
type. The null reference can always be cast to any reference type.
The null reference can always be assigned or cast to any reference type
In
practice, the programmer can ignore the null type and just pretend
that null is merely a special literal that can be of any reference
type
所以 null
的类型是 而不是 Object
,尽管它可以被转换为(读取为分配给)一个 Object
.
我正在使用代码:
System.out.println(null);
显示错误:
The method println(char[]) is ambiguous for the type PrintStream
为什么 null
不代表 Object
?
PrintStream
中有 3 个 println
方法接受引用类型 - println(char x[])
、println(String x)
、println(Object x)
.
当您通过null
时,所有3个都适用。方法重载规则优先选择具有最具体参数类型的方法,因此未选择 println(Object x)
。
然后编译器无法在前两个之间进行选择 - println(char x[])
和 println(String x)
- 因为 String
并不比 char[]
更具体,反之亦然。
如果要选择特定方法,请将 null 转换为所需类型。
例如:
System.out.println((String)null);
如果您调用 System.println(null)
有多个候选方法(带有 char []
、String
和 Object
参数)并且编译器无法决定采用哪一个.
修复
向 null 添加显式转换。
System.out.println((Object)null);
Why does't
null
represent Object?
来自JLS 4.1 The Kinds of Types and Values
There is also a special null type, the type of the expression null, which has no name.
Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type.
The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type.
The null reference can always be assigned or cast to any reference type
In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type
所以 null
的类型是 而不是 Object
,尽管它可以被转换为(读取为分配给)一个 Object
.