在Java中,null值可以被分配给一个对象的引用,表示该对象当前正在指向未知的数据。当程序试图访问这个引用时,将会抛出
NullPointerException。
那么如何避免程序抛出空指针异常?
1、避免去调用可能为null的对象的方法(静态方法除外)
String str = null;
if(str.equals("Test")) {
/* The code here will not be reached, as an exception will be thrown. */
}
这段代码必然抛出空指针异常,以下是正确的写法:
String str = null;
if("Test".equals(str)) {
/* Correct use case. No exception will be thrown. */
}
2、注意参数的检查
public static int getLength(String s) {
if (s == null)
throw new IllegalArgumentException("The argument cannot be null");
return s.length();
}
如上所示,当然,比如在常用的java开发中,也可以使用Hibernate Validator做参数验证。
3、尽量使用一些不会抛出空指针异常的方法
Object test = null;
test.toString()// 抛出异常
String.valueOf(test) // 正常
4、使用三目运算符
String message = (str == null) ? "" : str.substring(0, 10);
5、返回对象是列表的方法,返回一个空集合而不是null
public class Example {
private static List<Integer> numbers = null;
public static List<Integer> getList() {
if (numbers == null)
return Collections.emptyList();
else
return numbers;
}
}
6、借助一些工具类
比如Apache StringUtils
7、集合在get之前,检查一下是否存在
Map<String, String> map = …
…
String key = …
if(map.containsKey(key)) {
String value = map.get(key);
System.out.println(value.toString()); // No exception will be thrown.
}