Optional Or Fallback Chain
Build lazy fallbacks with Optional.or: each supplier runs only when the previous chain stage is empty, unlike eager orElse arguments.
Code
import java.util.Optional;
public class ConfigResolver {
static Optional<String> fromEnvironment() {
System.out.println("checking environment");
return Optional.empty(); // 演示:环境未配置
}
static Optional<String> fromFile() {
System.out.println("checking file");
return Optional.of("file-value");
}
static Optional<String> hardcoded() {
System.out.println("checking hardcoded");
return Optional.of("default-value");
}
public static void main(String[] args) {
// or 接收 Supplier:前一级为空才调用下一级,惰性求值
String value = fromEnvironment()
.or(ConfigResolver::fromFile)
.or(ConfigResolver::hardcoded)
.orElseThrow(() -> new IllegalStateException("no config"));
System.out.println("resolved = " + value);
}
}How the snippet works
The working surface is the class ConfigResolver and the functions fromEnvironment, fromFile, hardcoded and main — everything else is wiring.
Absence is modeled with Optional — the type system reminds you to check before unwrapping.
Applying it
Signature: static Optional<String> fromEnvironment()
The demo output is labeled (checking environment, checking file, checking hardcoded), so every printed line maps back to its originating operation.
Start the program and main runs fromEnvironment one after another.
Statements that matter
return Optional.empty(); // 演示:环境未配置
}
return Optional.of("default-value");
return Optional.of("file-value");
Interactive Tools for This Topic
FAQ
- What does Optional Or Fallback Chain print when run?
- Running the file directly is enough — expect labeled output lines such as `checking environment`, `checking file`, `checking hardcoded`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.