package Test10月.Test1007;
import org.junit.Test;
import java.util.Optional;
/**
* 功能描述:Optional类-可以防止出现空指针的类,可以为null
* @version 1.0
* @className Optional
* @author: 罗德
* @create: 2020-10-07 18:55
*/
public class OptionalTest {
/**
* 功能描述:实例化的方式:
* 1.of():返回描述给定非空值的可选值。
* 2.ofNullable():如果非空,则返回描述给定值的可选值,否则返回空的可选值。
* 方法参数描述:无
*/
@Test
public void test1() {
TEST test = new TEST();
/**
* public static <T> Optional<T> of(@NotNull T value)
* 返回描述给定非空值的可选值。
*/
Optional<Test10月.Test1007.TEST> optional = Optional.of(test);
System.out.println(optional);//Optional[TEST{name='null'}]
System.out.println("*******************");
test = null;
/**
* public static <T> Optional<T> ofNullable(@Nullable T value)
* 如果非空,则返回描述给定值的可选值,否则返回空的可选值。
*/
Optional<TEST> optional1 = Optional.ofNullable(test);
System.out.println(optional1);//Optional.empty
}
/**
* 功能描述:orElse()
* 如果存在值,则返回该值,否则返回其他值。
* 方法参数描述:无
*/
@Test
public void test2() {
TEST test = new TEST();
System.out.println(test);//TEST{name='null'}
Optional<TEST> optional = Optional.ofNullable(test);
/**
* public T orElse(T other)
* 如果存在值,则返回该值,否则返回其他值。
*/
TEST test2 = optional.orElse(new TEST("lld"));
System.out.println(test2);//TEST{name='null'}
System.out.println("****************");
test = null;
Optional<TEST> optional1 = Optional.ofNullable(test);
//如果test = null;则不会返回null,而是新创建的lld
TEST test3 = optional1.orElse(new TEST("lld"));
System.out.println(test3);//TEST{name='lld'}
}
}
class TEST {
private String name;
public TEST() {
}
public TEST(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TEST{" + "name='" + name + '\'' + '}';
}
}
04-15
218
04-07
2万+