防止NPE
- 返回类型为基本数据类型,return包装数据类型的对象时,自动拆箱有可能产生NPE。 反例:public int f() { return Integer对象}, 如果为null,自动解箱抛NPE
- 数据库的查询结果可能为null
- 集合里的元素即使isNotEmpty,取出的数据元素也可能为null
- 远程调用返回对象时,一律要求进行空指针判断,防止NPE
- 对于Session中获取的数据,建议进行NPE检查,避免空指针
- 级联调用obj.getA().getB().getC();一连串调用,易产生NPE
public final class Optional{ private static final Optional> EMPTY = new Optional<>(); private final T value; private Optional() { this.value = null; } private Optional(T value) { this.value = Objects.requireNonNull(value); } public static Optional ofNullable(T value) { return value == null ? empty() : of(value); } public static Optional of(T value) { return new Optional<>(value); } public static Optional empty() { @SuppressWarnings("unchecked") Optional t = (Optional ) EMPTY; return t; } ... ... }
ofNullable方法和of方法唯一区别就是当 value 为 null 时,ofNullable返回的是EMPTY,of 会抛出NullPointerException` 异常
ifPresent// 源码
public void ifPresent(Consumer super T> consumer) {
if (value != null)
consumer.accept(value);
}
public static void main(String[] args) {
Zoo zoo = new Zoo();
Dog dog = new Dog();
dog.setAge(1);
zoo.setDog(dog);
Optional.of(zoo).ifPresent(System.out::println);
}
isPresent
// 源码
public boolean isPresent() {
return value != null;
}
filter
Optional.of(zoo).filter(z -> z.getDog().getAge() > 0).ifPresent(System.out::println);map
// 源码
public Optional map(Function super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
public static void main(String[] args) {
UserRequest u1 = new UserRequest();
u1.setUserName("u1");
u1.setId(1L);
Optional.of(u1).map(new Function() {
@Override
public Object apply(UserRequest userRequest) {
return userRequest.getId();
}
}).ifPresent(System.out::println);
Optional aLong = Optional.of(u1).map(UserRequest::getId);
aLong.ifPresent(System.out::println);
}
flatMap
// 源码
public Optional flatMap(Function super T, Optional> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
与map不同的是,flagMap传入的Function的结果的是Optional,而map的是 U
Optional.ofNullable(student).flatMap(u -> Optional.ofNullable(u.getAge()));orElse
源码
public T orElse(T other) { return value != null ? value : other;}
传统方式
public static String getGender(Student student) { if (null == student) { return "Unkown"; } return student.getGender();}
优化
public static String getGender(Student student) { return Optional.ofNullable(student).map(u -> u.getGender()).orElse("Unkown");}
get
// 源码 public T get() { if (value == null) { throw new NoSuchElementException("No value present"); } return value;}
orElseGet
传入的是 Supplier接口
// 源码public T orElseGet(Supplier extends T> other) { return value != null ? value : other.get(); }
Optional.ofNullable(u1).map(u -> u.getId()).orElseGet(() -> "Unkown");orElseThrow
publicT orElseThrow(Supplier extends X> exceptionSupplier) throws X { if (value != null) { return value; } else { throw exceptionSupplier.get(); } }
Optional.ofNullable(student).map(u -> u.getGender()).orElseThrow(() -> new RuntimeException("Unkown"));



