使用单个null参数调用Java varargs方法? [英] Calling Java varargs method with single null argument?

查看:114
本文介绍了使用单个null参数调用Java varargs方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个vararg Java方法 foo(Object ... arg),我调用 foo(null,null),我有 arg [0] arg [1] as null 秒。但是,如果我调用 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 nulls. But if I call foo(null), arg itself is null. Why is this happening?

如何调用 foo ,以便 foo.length == 1&& ; foo [0] == null true

推荐答案

问题是当你使用文字null时,Java不知道它应该是什么类型。它可以是null Object,也可以是null Object数组。对于单个参数,它假定后者。

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]

这篇关于使用单个null参数调用Java varargs方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆