使用 null 对象获取对象的类型? [英] Get type of an object with an object of null?

查看:73
本文介绍了使用 null 对象获取对象的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码可以编译,但为什么会出现运行时异常?

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

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

我得到的错误是

java.lang.NullPointerException

即使设置为空,我如何获取对象的类型?

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

编辑我意识到没有对象存在,但仍然有一个字符串类型的对象 b.即使它没有对象,它仍然有一个类型.我如何获取对象的类型,无论它是否包含对象.

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.

推荐答案

当你有

String b = null;

您实际拥有的是一个引用类型 String 的变量,它引用了 null.您不能取消引用 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

这篇关于使用 null 对象获取对象的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆