Type of reference type with value null?

Alan Escreet picture Alan Escreet · Apr 19, 2011 · Viewed 10.9k times · Source

According to: http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html
4.5.2 Variables of Reference Type
A reference type can hold a null reference.

Is it possible to retrieve the declared type of the reference type when the assigned value is null?

Specifically, in a method that uses reflection, I wish the method to be null-safe and act on the original declared type (though I know the following code snippet doesn't work), for instance:

String referenceType = null;
MyReflectionClass.reflectionMethod(referenceType);
...
public static void reflectionMethod(Object referenceType) {
   Class<?> declaredType = referenceType.getClass();
}

I would not be averse to using generics to have type T instead of Object as the declared parameter type, if necessary.

Edit: I know that .getClass() works on the instance, not the declared type. I was wondering if it was possible to ask the reference for it's declared type. Since class hierarchies are static, there should be no problem to get that information.

Edit2: Here, the situation is made clear: Is Java "pass-by-reference" or "pass-by-value"?
Java is only pass-by-value, so even though a reference type is used, it is always handled as if the value (object instance) is passed (even though the internals only pass an object pointer). This means that Java doesn't actually have a reference type that knows about it's type (at least as far as the programmer is concerned), it's all in the value instances.
Therefore it is impossible to determine the type of any null value.

Answer

helloworld922 picture helloworld922 · Apr 19, 2011

In a single word, no. It doesn't make a whole lot of sense to try to find the members of a null reference, though, since null implies the absence of anything. You're probably better off just dis-allowing null as an input, probably by throwing a NullPointerException.

If you must handle null, perhaps the best way is to explicitly pass the class reference (or even better, a direct reference to the method in question).

public static void reflectionMethod(Object param, Class<?> referenceType) // null is dis-allowed for referenceType
{
    // ... no need to try to back-track the type from an object
}

If you can only ever get the null value, it's difficult (impossible unless there are other constraints imposed) to do much better than having a very lucky guess.