import org.junit.jupiter.api.Test; import java.util.Optional; /** * @Description Optional类测试 * @Author saq * @Date 2022/11/17 13:56 */ public class OptionalTest { /** * 当Optional.ofNullable()方法中的参数对象不为null时,走的是Optional.of()方法 * 调用person11.isPresent()时,对象不为空返回true */ @Test public void test1() { Person person1 = Person.builder().name("张三").age(30).build(); Optional<Person> person11 = Optional.ofNullable(person1); System.out.println(person11.isPresent()); } /** * 当Optional.ofNullable()方法中的参数对象为null时,走的是Optional.empty()方法 * 调用person21.isPresent()时,对象为空返回false */ @Test public void test2() { Person person2 = null; Optional<Person> person21 = Optional.ofNullable(person2); System.out.println(person21.isPresent()); } /** * 当Optional.ofNullable()方法中的参数对象不为null时,走的是Optional.of()方法 * 调用person11.ifPresent()时,对象不为空继续走下面的逻辑 */ @Test public void test3() { Person person1 = Person.builder().name("张三").age(30).build(); Optional<Person> person11 = Optional.ofNullable(person1); System.out.println(person11.get()); person11.ifPresent(person -> person.setName("李四")); System.out.println(person11.get()); } }
标签:ofNullable,初体验,person11,isPresent,System,Person,Optional From: https://www.cnblogs.com/sunAnqing/p/16899536.html