views:

236

answers:

4

How can you get the data type of a variable argument in Java if the varg is set to null? I use the getClass to retrieve the type. Is there any other way?

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

The only thing i could think of is using annotation from the calling function. Is there any other way?

+2  A: 

I'm not sure I understand what you are trying to do. Null has no class. If you want the static class of the variable used by the calling function, you can pass that class as an argument.

Maurice Perry
What I meant is the parameter used to pass is a variable of type (for example Date) but the date just so happens to be set to null when passed.
Nassign
The static type of the parameter is Object - it says so in the method's signature. The static type of the expression which evaluates to the argument passed in a call of the method isn't visible to the method.
Pete Kirkham
+2  A: 

You could use

if (arg == null)

to handle it as a special case and assign it a class, where Object or Void seem appropriate.

starblue
+2  A: 

We have stacked with the same problem to load data from DB and cast as expected. Unfortunately null has no type. Instead we have used generic wrapper, that always was non-null, but could contain the null value. In this case type info is available over wrapper's field.

Dewfy
Did you think of using the Void class, as I suggest in my answer?
KLE
+2  A: 

Let's split the question between the vararg and the null.

vararg

The point of varargs is to send an array of data without having them in the caller's code as an array, but as individual variables or constants.

Calling the varargs may not be very intuitive, here's what happens in various cases :

    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

Note that the third case is considered bad form. For example, you receive a warning if the null is a constant (not stored in a variable).

Note that in the fourth case, you are really looking for problems ! ;-)

Class of 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...
KLE