com.terheyden.event.CheckedConsumer Maven / Gradle / Ivy
Show all versions of event-router Show documentation
package com.terheyden.event;
import java.util.function.Consumer;
/**
* Represents an operation that accepts a single input argument and returns no
* result. Unlike most other functional interfaces, {@code Consumer} is expected
* to operate via side-effects.
*
* This is a functional interface
* whose functional method is {@link #accept(Object)}.
*
* @param the type of the input to the operation
*/
@FunctionalInterface
public interface CheckedConsumer extends Consumer {
/**
* Static method to create a {@link CheckedConsumer} from a lambda.
*/
static CheckedConsumer of(CheckedConsumer consumer) {
return consumer;
}
/**
* Accept the given item. Equivalent to {@link Consumer#accept(Object)},
* but allows throwing checked exceptions.
*/
void acceptChecked(T item) throws Throwable;
/**
* Unchecked version of {@link Consumer#accept(Object)}.
* Use this just as you would use {@link Consumer#accept(Object)}.
* Any checked exceptions will be rethrown as unchecked automatically.
*
* @param item the input argument
*/
@Override
default void accept(T item) {
try {
acceptChecked(item);
} catch (Throwable t) {
CheckedConsumerInternal.throwUnchecked(t);
}
}
}
/**
* Defines a self-contained unchecked throw method.
*/
interface CheckedConsumerInternal {
@SuppressWarnings("unchecked")
static R throwUnchecked(Throwable t) throws T {
throw (T) t;
}
}