Optional是JAVA8引入的類,它其實是一個包裝類,可以對所有對象進行包裝, 包括null,這個特性使得我們編碼可以優雅的解決空指針異常。
先編寫一些測試類
class Student { private ClassRoom classRoom; public ClassRoom getClassRoom() { return classRoom; } public void setClassRoom(ClassRoom classRoom) { this.classRoom = classRoom; } } class ClassRoom { private Seat seat; public Seat getSeat() { return seat; } public void setSeat(Seat seat) { this.seat = seat; } } class Seat { private Integer row; private Integer column; public Integer getRow() { return row; } public void setRow(Integer row) { this.row = row; } public Integer getColumn() { return column; } public void setColumn(Integer column) { this.column = column; } }
先來看看以前傳統我們編碼怎么避免空指針異常的
Student student = new Student(); if (student != null) { ClassRoom classRoom = student.getClassRoom(); if (classRoom != null) { Seat seat = classRoom.getSeat(); if (seat != null) { Integer row = seat.getRow(); System.out.println(row); } } }
如果使用Optional的代碼
Student student = new Student(); Integer row = Optional.ofNullable(student) .map(Student::getClassRoom) .map(ClassRoom::getSeat) .map(Seat::getRow) .orElse(null); System.out.println(row);
重點在於orElse方法
public T orElse(T other) { return value != null ? value : other; }
方法里面做了非空判斷,我們就可以傳入一個如果對象為空時候的默認值;
可以看出Optional的方法許多都返回Optional對象,所以它支持鏈式調用;
而且大多方法入參都是Supplier 函數式接口,因此支持java8的JAVA Lambda表達式。