八、Optional 类
1、 作用:可以存放空指针null,主要用于解决空指针问题。
2、 使用方法
1) 创建对象(2种方法)
Optional optional = Optional.of(非null对象);
或者
Optional optional = Optional.ofNullable(任何对象);
2) 判断对象是否为null(1种方法)
Optional对象.isPresent();
3) 获取对(3种方法)
Optional对象.get();
Optional对象.orElse()
Optional对象.orElseGet();
例子:
package com.lennar.jdk8learn.learn; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.junit.Test; import java.util.Optional; import java.util.function.BiFunction; public class LearnOptional { @Test public void test() { //1.创建 try { Optionaloptional1 = Optional.of(null);//如果是null,则报空指针异常的错误 } catch (Exception e) { System.out.println("optional1报错:" + e.toString()); } try { Optional optional2 = Optional.ofNullable(null);//允许存放null,不会报空指针的错误 } catch (Exception e) { System.out.println("optional1报错:" + e.toString()); } //2.空指针判断 Optional optional3 = Optional.ofNullable(null); if (!optional3.isPresent()) {//null时返回false,非null时返回true System.out.println("这个是null"); } Optional optional4 = Optional.ofNullable(new String("")); if (!optional4.isPresent()) {//null时返回false,非null时返回true System.out.println("这个是null"); } else { System.out.println("这个不是null"); } //3.获取Optional中的对象 try { Teacher t0 = optional3.get();//确定有对象时返回对象,否则报空指针异常的错 System.out.println(t0); } catch (Exception e) { System.out.println("optional3中没有对象,为null"); } Optional optional5 = Optional.ofNullable(new Teacher("1", "张三")); Teacher t1 = optional5.get(); System.out.println(t1); Teacher t2 = optional3.orElse(new Teacher("2", "李四"));//对象非空返回对象,否则返回默认值(类型一致,在orElse中的值就是默认值) System.out.println(t2); Teacher t3 = optional5.orElse(null); System.out.println(t3); Teacher t4 = optional3.orElseGet(() -> {//对象非空返回对象,否则调用orElseGet中的方法返回同类型的默认对象 String id = "3"; String name = "王五"; BiFunction function = Teacher::new; return function.apply(id, name); }); System.out.println(t4); Teacher t5 = optional5.orElseGet(() -> { String id = "4"; String name = "赵六"; BiFunction function = Teacher::new; return function.apply(id, name); }); System.out.println(t5); } } @Data @AllArgsConstructor @NoArgsConstructor class Teacher { private String id; private String name; }