JAVA - 【Optional】辅助防止空指针异常
程序员文章站
2022-03-04 11:28:38
...
Optional是JDK1.8新增的类,在JDK1.8之前一般某个函数应该返回非空对象,但是偶尔会返回null,在JDK1.8中,不推荐直接返回该对象,返回之前需要进行处理;
☞ 关键:Optional.ofNullable(s).get()
- 一般情况
☞ 由于对象元素没有初始化,运行会直接在s.getName处报空指针异常,但是究竟是哪一个deal造成的空指针异常?
public class Main{
public static void main(String[] args) {
Student s = new Student();
s = deal1(s);
s = deal2(s);
s = deal2(s);
String name = s.getName();
System.out.println(name);
}
public static Student deal1(Student s){
s = null;
return s;
}
public static Student deal2(Student s){
s = null;
return s;
}
public static Student deal3(Student s){
s = null;
return s;
}
}
- Optional优化
import java.util.Optional;
public class Main{
public static void main(String[] args) {
Student s = new Student();
s = deal1(s);
s = deal2(s);
s = deal2(s);
String name = s.getName();
System.out.println(name);
}
public static Student deal1(Student s){
s = null;
return Optional.ofNullable(s).get();
}
public static Student deal2(Student s){
s = null;
return Optional.ofNullable(s).get();
}
public static Student deal3(Student s){
s = null;
return Optional.ofNullable(s).get();
}
}
推荐阅读
-
利用Java8 Optional如何避免空指针异常详解
-
利用Java8 Optional如何避免空指针异常详解
-
在Java8中如何风骚走位的避开空指针异常
-
荐 java程序员最常见的空指针异常java.lang.NullPointerException
-
Java自动拆箱空指针异常,救火队员上线
-
Java中构造方法、空指针异常现象、基本数据类型和引用数据类型作为参数传递的区别
-
Java自动拆箱空指针异常的解决
-
空指针异常,算得上是一个简单低级的错误吧 java.lang.NullPointerException: null
-
Java开发笔记(七十七)使用Optional规避空指针异常
-
Java8 新特性 | 如何风骚走位防止空指针异常