Get type of an object with an object of null?

14,918

Solution 1

When you have

String b = null;

what you actually have is a variable of reference type String that is referencing null. You cannot dereference null to invoke a method.

With local variables you cannot do what you are asking.

With member variables, you can use reflection to find the declared type of the field.

Field field = YourClass.class.getDeclaredField("b");
Class<?> clazz = field.getType(); // Class object for java.lang.String

Solution 2

Everyone else has appropriately answered that there is no type as there is no object but if I'm reading this correctly, I think what you are really asking is about how to check the type that your variable has been assigned.

For that I would refer to this link: How to check type of variable in Java?

Solution 3

There is no object here, and null has no type.
You can't do that.

Solution 4

A variable is not the same as an object. A variable is a reference to an object.

You get a NullPointerException if you try to dereference a null reference (i.e., if you try to call a method or access a member variable through a null reference).

When a variable is null, it means it refers to no object. Ofcourse you can't get the type of "no object".

Share:
14,918

Related videos on Youtube

Monte Carlo
Author by

Monte Carlo

Free the mallocs.

Updated on October 30, 2022

Comments

  • Monte Carlo
    Monte Carlo over 1 year

    The following code does compile, but why do I get a run time exception?

    String b = null;
    System.out.println(b.getClass());
    

    Error I get is

    java.lang.NullPointerException
    

    How can I get the type of the object even if it's set to null?

    Edit I realize there is no object present, but there still is an object b of type String. Even if it holds no object, it still has a type. How do I get at the type of an object, regardless of if it holds an object or if it does not.

    • Sotirios Delimanolis
      Sotirios Delimanolis over 10 years
      It doesn't have a type, it is null.