Determine type of a variable whose value is NULL

B

brian.vanheesch

I have a variable defined (local, global, parameter, field; it does
matter) such as:

MyClass abc=null;
MyClass def=new MyClass();

The variables above will house an object of type MyClass or any
subclass. Now in code, I would like to determine the specific type of
the variable. So I can do:

System.out.println(def.getClass().getName());

but what can I do for variable 'abc' ? Using the same syntax for
variable abc, will naturally result in an NullPointerException.

Is there a typeof syntax similar to instanceof?
 
L

Lew

I have a variable defined (local, global, parameter, field; it does
matter) such as:

MyClass abc=null;
MyClass def=new MyClass();

The variables above will house an object of type MyClass or any
subclass. Now in code, I would like to determine the specific type of
the variable. So I can do:

System.out.println(def.getClass().getName());

but what can I do for variable 'abc' ? Using the same syntax for
variable abc, will naturally result in an NullPointerException.

Is there a typeof syntax similar to instanceof?

No. Why does instanceof not help you?

<http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.20.2>

abc can be tested with the instanceof operator, in which case null will return
fallse for (abc instanceof MyClass), but more usefully just test it for null
first, as in
if ( abc == null )
{
// handle null
}
else ...

The literal null has only one type.
There is also a special /null/ type, the type of the expression null, which has no name.
[emph. orig.]
 
M

Mike Schilling

I have a variable defined (local, global, parameter, field; it does
matter) such as:

MyClass abc=null;
MyClass def=new MyClass();

The variables above will house an object of type MyClass or any
subclass. Now in code, I would like to determine the specific type of
the variable. So I can do:

System.out.println(def.getClass().getName());

but what can I do for variable 'abc' ?

System.out.println( abc == null ? "<null>" : abc.getClass().getName());
 
R

Roedy Green

Is there a typeof syntax similar to instanceof?

null variables don't have a class.

You can do something like this

Skurtlewax w = null;

System.out.println( Skurltewax.class );
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top