使用单个空参数调用 Java varargs 方法? [英] Calling Java varargs method with single null argument?
问题描述
如果我有一个可变参数 Java 方法 foo(Object ...arg)
并且我调用 foo(null, null)
,我有两个 arg[0]
和 arg[1]
作为 null
s.但是如果我调用 foo(null)
,arg
本身就是 null.为什么会这样?
If I have a vararg Java method foo(Object ...arg)
and I call foo(null, null)
, I have both arg[0]
and arg[1]
as null
s. But if I call foo(null)
, arg
itself is null. Why is this happening?
我应该如何调用 foo
使得 foo.length == 1 &&foo[0] == null
是 true
吗?
How should I call foo
such that foo.length == 1 && foo[0] == null
is true
?
推荐答案
问题在于,当您使用文字 null 时,Java 不知道它应该是什么类型.它可能是一个空对象,也可能是一个空对象数组.对于单个参数,它假定后者.
The issue is that when you use the literal null, Java doesn't know what type it is supposed to be. It could be a null Object, or it could be a null Object array. For a single argument it assumes the latter.
你有两个选择.将 null 显式转换为 Object 或使用强类型变量调用该方法.请看下面的例子:
You have two choices. Cast the null explicitly to Object or call the method using a strongly typed variable. See the example below:
public class Temp{
public static void main(String[] args){
foo("a", "b", "c");
foo(null, null);
foo((Object)null);
Object bar = null;
foo(bar);
}
private static void foo(Object...args) {
System.out.println("foo called, args: " + asList(args));
}
}
输出:
foo called, args: [a, b, c]
foo called, args: [null, null]
foo called, args: [null]
foo called, args: [null]
这篇关于使用单个空参数调用 Java varargs 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!