java8中的Optional容器类,避免空指针异常
程序员文章站
2022-06-07 12:36:11
...
java8中使用Optional容器类来尽可能的避免或快速定位空指针异常
Optional类的基本使用
public class Person {
private Integer age;
private Double salary;
public Person() {
}
public Person(Integer age, double salary) {
this.age = age;
this.salary = salary;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
", salary=" + salary +
'}';
}
}
//of方法 创建一个Optional对象
Optional<Person> of = Optional.of(new Person());
Optional<Person> of1 = Optional.of(null);
System.out.println(of.get());
System.out.println(of1.get());//java.lang.NullPointerException
//empty方法 创建一个空的Optional实例
Optional<Person> empty = Optional.empty();
System.out.println(empty.get()); //java.util.NoSuchElementException: No value present
//ofNullable(T t) 如果T不为空,创建Optional实例,如果为空,创建空实例,下面就是这个方法的实现,综合了上面两个方法
// public static <T> Optional<T> ofNullable(T value) {
// return value == null ? empty() : of(value);
// }
Optional<Person> ofNullable = Optional.ofNullable(new Person());
//isPersent方法 判断是否包含空值
Optional<Person> isPer= Optional.ofNullable(new Person());
//如果不为空 输出
if(isPer.isPresent()){
System.out.println(isPer.get());
}
//orElse(T t) 如果调用对象包含值 返回该值,否则返回t
Optional<Person> orEl = Optional.ofNullable(null);
System.out.println(orEl.orElse(new Person(12, 222))); //输出 Person{age=12, salary=222.0}
//orElseGet(Supplier s) 如果调用对象包含值 返回该值,否则返回s获取的值
Optional<Object> orEG = Optional.ofNullable(null);
System.out.println(orEG.orElseGet(() -> new Integer(33))); //输出33
//map(Function f) 如果有值 对其处理,并返回处理后的Optional,否则返回Optional.empty()
Optional<Person> oMap = Optional.ofNullable(new Person(12, 2222));
Optional<Integer> oAge = oMap.map(e -> e.getAge());
System.out.println(oAge.get()); //输出12
//flatMap(Function mapper) 与map类似,就是返回值必须是Optional 进一步避免空指针异常
Optional<Person> oFlatMap = Optional.ofNullable(new Person(12, 2222));
Optional<Integer> oFlatAge = oMap.flatMap(e -> Optional.of(e.getAge()));
System.out.println(oAge.get()); //输出12
这里放一个例子
有一个Teacher类,Teacher中有一个Student属性,
public class Teacher {
private Optional<Student> student = Optional.empty();
public void setStudent(Optional<Student> student) {
this.student = student;
}
public Optional<Student> getStudent() {
return student;
}
}
Student类有一个name属性
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
使用Optional容器来避免空指针异常
public static void main(String[] args) {
Optional<Teacher> op = Optional.ofNullable(null);
String studentName = getStudentName(op);
System.out.println(studentName);
}
public static String getStudentName(Optional<Teacher> teacher){
return teacher.orElse(new Teacher())
.getStudent()
.orElse(new Student("小明"))
.getName();
}