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.