工作中使用Optional处理空指针异常
- 实体类
- 以前对空指针的判断
- Optional处理空指针
- 测试结果
实体类
package po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
/**
* 姓名
*/
private String name;
/**
* 地址
*/
private Address address;
}
package po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@Data
@NoArgsConstructor
public class Address {
/**
* 城市
*/
private String city;
}
以前对空指针的判断
package com.demo;
import po.Address;
import po.Student;
public class TestCase {
public static void main(String[] args) {
Student student = new Student("张三",new Address("香港"));
student = null;
if (null != student){
Address address = student.getAddress();
if (null != address){
if (null != address.getCity()){
System.out.println(address.getCity());
}
}
}
throw new RuntimeException("学生地址信息不能为空");
}
}
Optional处理空指针
package com.demo;
import po.Address;
import po.Student;
import java.util.Optional;
public class TestCase2 {
public static void main(String[] args) {
Student student = new Student("张三", new Address("香港"));
student = null;
String address =
Optional.ofNullable(student)
.map(Student::getAddress)
.map(Address::getCity)
.orElseThrow(() -> new RuntimeException("学生地址信息不能为空"));
System.out.println(address);
}
}
测试结果
student为null,
抛出空指针异常
不为空指针异常的时候,输出字符串