JDK1.8新特性-Optional
1.Optional
1.1 概念
Optional和Stream流一样,是JAVA8的新成员;它可以使代码中对NULL对象的处理更加优雅且高效;
1.2 方法介绍
1.2.1 创建Optional对象
of():静态方法,传入一个对象,若该对象是null,会抛出空指针异常;
public static <T> Optional<T> of(T value) {
return new Optional(value);
}
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
ofNullable:静态方法,传入一个对象,若该对象是null,会返回一个空的Optional对象;
private static final Optional<?> EMPTY = new Optional();
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
public static <T> Optional<T> empty() {
Optional<T> t = EMPTY;
return t;
}
1.2.2 判断Optional对象是否包含对象
isPresent():成员方法,若Optional对象中包含对象则返回true,反之返回false;
public boolean isPresent() {
return this.value != null;
}
ifPresent(Consumer<? super T> action):成员方法,若包含对象则执行action的方法
public void ifPresent(Consumer<? super T> action) {
if (this.value != null) {
action.accept(this.value);
}
}
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction):成员方法,包含对象则执行action,反之启动emptyAction线程
public void ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) {
if (this.value != null) {
action.accept(this.value);
} else {
emptyAction.run();
}
}
isEmpty():成员方法,正好与isPresetn()相反,包含对象返回false,反之返回true;
public boolean isEmpty() {
return this.value == null;
}
1.2.3 获取Optional容器得到对象
get(): 如果调用对象包含值,返回该值,反之抛出异常
public T get() {
if (this.value == null) {
throw new NoSuchElementException("No value present");
} else {
return this.value;
}
}
orElse(T other):若有值则返回,反之返回other
public T orElse(T other) {
return this.value != null ? this.value : other;
}
orElseGet(Supplier<? extends T> supplier):若有值则返回,反之返回supplier提供的对象
public T orElseGet(Supplier<? extends T> supplier) {
return this.value != null ? this.value : supplier.get();
}
orElseThrow(Supplier<? extends X> exceptionSupplier):若有值则返回,反之抛出由supplier提供的异常
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (this.value != null) {
return this.value;
} else {
throw (Throwable)exceptionSupplier.get();
}
}
orElseThrow():若有值则返回,反之抛出Optional提供的异常
public T orElseThrow() {
if (this.value == null) {
throw new NoSuchElementException("No value present");
} else {
return this.value;
}
}