Get object type with null object?

The following code compiles, but why am I getting a runtime exception?

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

Error:

 java.lang.NullPointerException 

How can I get the type of an object even if it is set to null?

Edit I understand that there is no object, but there is still an object b of type String. Even if it does not contain an object, it still has a type. How to get the type of an object, whether it contains an object or not.

+6
source share
6 answers

If you

 String b = null; 

that you actually have a variable of reference type String , which refers to null . You cannot cast null to call a method.

With local variables, you cannot do what you ask.

With member variables, you can use reflection to search for a declared field type.

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

There is no object, and null has no type.
You cannot do this.

+2
source

The variable does not match the variable. A variable is a reference to an object.

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

When the variable is null , it means that it does not apply to the object. Of course, you cannot get the type "no object".

+2
source

Everyone else correctly answered that there is no type, since there is no object, but if I read it correctly, I think that you are really asking how to check the type that your variable has been assigned.

For this, I would call this link: How to check the type of a variable in Java?

+2
source

Null references have no type. For an object that is not referenced, you cannot call .getClass() on a nonexistent object.

If you are looking for a compile time type, you can write String.class .

0
source

To answer your question, you must understand what you wrote.

String b = null; can translate to. Reserve in memory space for the String class and fill it with zero.

So there is no object in this expression. This is why you get a NullPointerException.

To get the type of such an declaration, you can use the reflection mechanism, but it applies only to members of the class.

0
source

Source: https://habr.com/ru/post/959330/


All Articles