主要解决的问题是空指针异常(NullPointerException)
本质是⼀个包含有可选值的包装类,这意味着 Optional 类既可以含有对象也可以为空
# null 值作为参数传递进去,则会抛异常
import java.util.Optional;
public class Main {
public static void main(String[] args) throws Exception {
# 会抛出异常
Student student = null
Optional<Student> opt = Optional.of(student);
# 不会抛出异常
Student student = new Student();
Optional<Student> opt = Optional.of(student);
}
}
# 如果对象即可能是 null 也可能是⾮ null,应该使⽤ ofNullable() ⽅法
# 如果值存在则isPresent()⽅法会返回true,调⽤get()⽅法会返回该对象⼀般使⽤get之前需要先验证是否有值,不然还会报错
import java.util.Optional;
public class Main {
public static void main(String[] args) throws Exception {
Student student = new Student();
Optional<Student> opt = Optional.ofNullable(student);
if(opt.isPresent()){
System.out.println("optional不为空");
Student s = opt.get();
}else {
System.out.println("optional为空");
}
}
}
# 设置默认值,用于兜底
# 如果有值则返回该值,否则返回传递给它的参数值
import java.util.Optional;
public class Main {
public static void main(String[] args) throws Exception {
Student student1 = null;
Student student2 = new Student(2);
Student result = Optional.ofNullable(student1).orElse(student2);
System.out.println(result.getAge());
}
}
import java.util.Optional;
public class Main {
public static void main(String[] args) throws Exception {
Student student = null;
int result = Optional.ofNullable(student).map(obj->obj.getAge()).orElse(4);
System.out.println(result);
}
}