在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();
}
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.
}
8、Optional类
public static void main(String[] args) {
List<String> list = null;
list.forEach(x -> System.out.println(x));
}
工作中经常会遇到,查询返回空,如果没有判空处理,一不小心就会空指针异常。加上if判断处理也可以,但是jdk1.8有更优雅的处理方式。
public static void main(String[] args) {
List<String> list = null;
List<String> newList = Optional.ofNullable(list).orElse(Lists.newArrayList());
newList.forEach(x -> System.out.println(x));
}
先解释代码含义:如果list集合不为空,将list集合赋值给newList;如果list集合为空创建一个空对象集合赋值给newList,保证list集合永远不为空,也就避免了空指针异常。(为了更好的理解,分开写了,比较庸俗,实际工作中都是一行搞定,哈哈哈)
再看看源码:底层是怎么处理的,怎么就避免了空指针呢?
//静态变量 empty
private static final Optional<?> EMPTY = new Optional<>();
//如果对象为空,执行empty()方法;不为空,执行of(value)方法
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
1.首先执行ofNullable()方法,如果T对象为空,执行empty()方法;不为空,执行of(value)方法;
2.empty()方法,初始化一个空对象Optional(空对象和null不是一回事哈);
3.of(value)方法,将泛型对象T用于Optional构造方法的参数上,返回一个有值的对象
4.经过上面两步,从而保证了Optional不为null,避免了空指针;
Optional类 Optional.flatmap和Optional.map之间的区别:
使用map函数返回对象,使用flatMap返回Optional。例如:
public static void main(String[] args) {
Optional<String> s = Optional.of("input");
System.out.println(s.map(Test::getOutput));
System.out.println(s.flatMap(Test::getOutputOpt));
}
static Optional<String> getOutputOpt(String input) {
return input == null ? Optional.empty() : Optional.of("output for " + input);
}
static String getOutput(String input) {
return input == null ? null : "output for " + input;
}