支持检查异常的 Java 8+ 功能接口 + 适配器
Checked-exception-enabled Java functional interfaces — a zero-dependency drop-in for java.util.function.
Java's java.util.function interfaces don't support checked exceptions, turning clean one-liners into verbose try-catch blocks:
// what you want
.map(path -> new URI(path))
// what Java forces you to write
.map(path -> {
try {
return new URI(path);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
})throwing-function provides checked-exception-aware variants of all standard functional interfaces:
ThrowingFunction toUri = URI::new;And adapters to integrate them into standard Java APIs:
stream.map(ThrowingFunction.unchecked(URI::new))
.forEach(System.out::println);| Interface | Functional method |
|---|---|
ThrowingFunction |
R apply(T t) throws E |
ThrowingBiFunction |
R apply(T1 t1, T2 t2) throws E |
ThrowingUnaryOperator |
T apply(T t) throws E |
ThrowingBinaryOperator |
T apply(T t1, T t2) throws E |
ThrowingConsumer |
void accept(T t) throws E |
ThrowingBiConsumer |
void accept(T t, U u) throws E |
ThrowingSupplier |
T get() throws E |
ThrowingPredicate |
boolean test(T t) throws E |
ThrowingBiPredicate |
boolean test(T t, U u) throws E |
ThrowingRunnable |
void run() throws E |
ThrowingToLongFunction |
long applyAsLong(T t) throws E |
Each interface provides static adapter methods to bridge Throwing* instances into standard java.util.function types.
unchecked — wrap in CheckedExceptionWraps the checked exception in a CheckedException (a RuntimeException subclass) and rethrows it. Available on all interfaces.
stream.map(ThrowingFunction.unchecked(URI::new))
.forEach(System.out::println);sneaky — rethrow without wrappingRethrows the checked exception as-is, bypassing the compiler's checked-exception enforcement via type erasure. Available on all interfaces.
stream.map(ThrowingFunction.sneaky(URI::new))
.forEach(System.out::println);lifted / optional — return OptionalReturns the result wrapped in an Optional, or Optional.empty() on exception. No exception is propagated.
ThrowingFunction.lifted(f) → Function>ThrowingBiFunction.optional(f) → BiFunction>ThrowingSupplier.optional(s) → Supplier>stream.map(ThrowingFunction.lifted(URI::new)) // Stream>
.forEach(System.out::println);
com.pivovarit
throwing-function
1.6.1
implementation 'com.pivovarit:throwing-function:1.6.1'None. Implemented using core Java libraries only.
暂无开放 Issues,或尚未同步最近议题。