Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of an object with an object of null?

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.

like image 540
Monte Carlo Avatar asked Dec 04 '13 14:12

Monte Carlo


People also ask

Is null an object type?

In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can consider it a bug in JavaScript that typeof null is an object.

How do you find a null object?

In order to check whether a Java object is Null or not, we can either use the isNull() method of the Objects class or comparison operator.

When using the JavaScript typeof () operator What does a value of null mean?

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

What will be the return value of typeof null?

it has one value: null. it does not have a constructor.


1 Answers

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
like image 195
Sotirios Delimanolis Avatar answered Sep 28 '22 08:09

Sotirios Delimanolis