Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
OptionalTest.java
package com.klvchen.java4;
import org.junit.Test;
import java.util.Optional;
public class OptionalTest {
/*
Optional.of(T t) : 创建一个 Optional 实例,t 必须非空;
Optional.empty() : 创建一个空的 Optional 实例
Optional.ofNullable(T t): t 可以为 null
*/
@Test
public void test1(){
Girl girl = new Girl();
girl = null;
Optional<Girl> optionalGirl = Optional.of(girl);
}
@Test
public void test2(){
Girl girl = new Girl();
girl = null;
//ofNullable(T t): t可以为null
Optional<Girl> optionalGirl = Optional.ofNullable(girl);
System.out.println(optionalGirl);
// orElse(T t1):如果当前的optional内部封装的t是非空的,则返回内部的t.
// 如果内部的是空的,则返回orElse()方法中的参数t1.
Girl girl1 = optionalGirl.orElse(new Girl("赵丽颖"));
System.out.println(girl1);
}
public String getGirlName(Boy boy){
return boy.getGirl().getName();
}
@Test
public void test3(){
Boy boy = new Boy();
boy = null;
String girlName = getGirlName(boy);
System.out.println(girlName);
}
//优化以后的getGirlName():
public String getGirlName1(Boy boy) {
if (boy != null) {
Girl girl = boy.getGirl();
if (girl != null) {
return girl.getName();
}
}
return null;
}
@Test
public void test4(){
Boy boy = new Boy();
boy = null;
String girlName = getGirlName1(boy);
System.out.println(girlName);
}
//使用Optional类的getGirlName():
public String getGirlName2(Boy boy) {
Optional<Boy> boyOptional = Optional.ofNullable(boy);
Boy boy1 = boyOptional.orElse(new Boy(new Girl("迪丽热巴")));
Girl girl = boy1.getGirl();
Optional<Girl> girlOptional = Optional.ofNullable(girl);
Girl girl1 = girlOptional.orElse(new Girl("古力娜扎"));
return girl1.getName();
}
@Test
public void test5(){
Boy boy = null;
boy = new Boy();
boy = new Boy(new Girl("苍老师"));
String girlName = getGirlName2(boy);
System.out.println(girlName);
}
}
OptionalTest2.java
package com.klvchen.java;
import org.junit.Test;
import java.lang.annotation.Target;
import java.util.Optional;
public class OptionalTest2 {
@Test
public void test1(){
Optional<Object> op1 = Optional.empty();
if (!op1.isPresent()){//Optional 封装的数据是否包含数据
System.out.println("数据为空");
}
System.out.println(op1);
System.out.println(op1.isPresent());
//如果Optional封装的数据value为空,则get()报错。否则,value不为空时,返回value,
//System.out.println(op1.get());
}
@Test
public void test2(){
String str = "hello";
str = null;
//of(T t):封装数据 t 生成 optional 对象。要求 t 非空,否则报错。
Optional<String> op1 = Optional.of(str);
//get()通常与of()方法搭配使用。用于获取内部的封装的数据vaLue
String str1 = op1.get();
System.out.println(str1);
}
@Test
public void test3(){
String str = "beijing";
str = null;
//ofNullable(T t):封装数据t赋给Optional内部的value。不要求t非空
Optional<String> op1 = Optional.ofNullable(str);
//orELse(T t1):如果Optional内部的value非空,则返回此vaLue值。如果
//value为空,则返回t1.
String str2 = op1.orElse("shanghai");
System.out.println(str2);
}
}