在使用Java Supplier接口時(shí),可以通過以下方式避免空指針異常:
Supplier<String> supplier = () -> "Hello World";
Optional<String> optional = Optional.ofNullable(supplier.get());
optional.ifPresent(System.out::println);
Supplier<String> supplier = () -> null;
String result = supplier.get();
if (result != null) {
System.out.println(result);
} else {
System.out.println("Supplier returned null");
}
Supplier<String> supplier = () -> "Hello World";
String result = Objects.requireNonNull(supplier.get(), "Supplier returned null");
System.out.println(result);
通過以上方式,可以有效避免空指針異常在使用Java Supplier接口時(shí)的發(fā)生。