Get type of an object with an object of null?

拟墨画扇 提交于 2019-12-05 00:44:22

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

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

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".

DanK

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?

Null references don't have a type. There's no object being pointed to, so you can't call .getClass() on the non-existent object.

If you're looking for the compile-time type, you can write String.class instead.

To answer to your question you must understand what have you written.

String b = null; can be translated to. Reserve in memory space for a String class and fill it with null.

So there is not object in that statement. That is why you get NullPointerException.

To retrieve the type of such declaration you can use reflection mechanism but it only apply to class members.

As the above answas state correcty, this is not possible. The closest I came up with is this:

<T extends Object> String typeAndValue(Class<T> type, T value) {
    return type.getClass.getSimpleName() + " is: " + String.valueOf(value);
}

You need to explicitly pass the type, but you cannot pass anything different than a suitable type (still may be supperclass) because it would not compile.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!