0

如果 varg 设置为 null,如何在 Java 中获取变量参数的数据类型?我使用 getClass 来检索类型。还有其他方法吗?

public void method(String name, Object ... vargs)
{
    for(Object arg : vargs)
    {
        mapType.put(arg.getClass());
        mapVal.put(arg);
    }
}

我唯一能想到的是使用调用函数中的注释。还有其他方法吗?

4

4 回答 4

2

我不确定我是否理解您要执行的操作。Null 没有类。如果您想要调用函数使用的变量的静态类,您可以将该类作为参数传递。

于 2009-10-02T08:42:13.167 回答
2

你可以使用

if (arg == null)

将其作为特殊情况处理并为其分配一个类,其中 Object 或 Void 似乎合适。

于 2009-10-02T08:50:26.773 回答
2

我们遇到了同样的问题来从数据库加载数据并按预期进行转换。不幸的是 null 没有类型。相反,我们使用了通用包装器,它总是非空的,但可以包含空值。在这种情况下,类型信息可通过包装器的字段获得。

于 2009-10-02T08:53:30.260 回答
2

让我们在可变参数和空值之间拆分问题。

可变参数

可变参数的重点是发送数据数组,而不是在调用者的代码中将它们作为数组,而是作为单独的变量或常量。

调用可变参数可能不是很直观,以下是各种情况下发生的情况:

    method("", "1", "2"); // vargs is {"1", "2"}
    method(""); // vargs is {}, the empty array (it is not null)
    method("", null); // vargs is {null}, size 1 array containing the element 'null'
    method("", (Object[])null); // vargs is null, a null instance

请注意,第三种情况被认为是错误的形式。例如,如果 null 是常量(未存储在变量中),您会收到警告。

请注意,在第四种情况下,您确实在寻找问题!;-)

空类

Now, we are talking of an array that contains a null value, not about a null array (that was sorted out in the previous part).

General case

Null can be of any class (all at a time). But instanceof will always return false.

Put into a map

If one value is null, you need to think about what you want to do. Obviously, getClass() cannot be called on a null value. So you can choose between:

  1. skip the null value, not add it in the map
  2. choose a class you want to associate to null. This could be Object, or Void, or another specific classe. Think about what you want to do with it, because the association is arbitrary...
于 2009-10-02T09:22:25.553 回答