关于null的思考

关于null的思考

写代码的时候有个地方需要把 Integer 类型强转为 String

Integer firstEventType = eventTask.getEventType1();
String firstEventTypeName = eventTypeService.queryDescByCode(String.valueOf(firstEventType));

当我点开 String#valueof 这个静态方式时

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

当我们没有获取到 firstEventType 这个值时,为 null,此时它返回给我们的是字符串 “null” ,有时候就不符合我们的业务场景,最好是提前做空值判断。

看下面一个例子

Integer i = null;
System.out.println(String.valueOf(i)); // 输出 null
System.out.println(String.valueOf(null)); // 空指针

感觉很奇怪,竟然输出结果不一样。

看看这两个重载方法

public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}

public static String valueOf(char data[]) {
return new String(data);
}

凭直觉来看以为String.valueOf(null) 会选择第一做为 valueOf(Object obj) 这个从载方法,然而选择的是valueOf(char data[]) 所以会报空指针异常。

下面是查到官方文档 https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5

如果第一个方法处理的任何调用都可以传递给另一个没有编译时类型错误的调用,那么一个方法比另一个方法更具体。

从意思来看 valueOf(char data[])valueOf(Object obj) 更具体。

我们非常痛恨的 null 到底是什么

Java 语言定义

There is also a special null type, the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type.

Comments