
de.larssh.utils.function.ThrowingSupplier Maven / Gradle / Ivy
package de.larssh.utils.function;
import java.util.function.Supplier;
import de.larssh.utils.SneakyException;
import edu.umd.cs.findbugs.annotations.Nullable;
/**
* Represents a supplier of results. There is no requirement that a new or
* distinct result be returned each time the supplier is invoked.
*
*
* {@code ThrowingSupplier}s can throw any kind of {@link Exception}. When used
* as {@link Supplier} exceptions are hidden from compiler.
*
*
* This is a functional interface whose
* functional method is {@link #get()}.
*
* @param the type of results supplied by this supplier
*/
@FunctionalInterface
public interface ThrowingSupplier extends Supplier {
/**
* Short-hand method to cast any {@link ThrowingSupplier} as {@link Supplier}.
*
* @param supplier throwing supplier
* @param the type of results supplied by this supplier
* @return hidden throwing supplier
*/
static Supplier throwing(final ThrowingSupplier supplier) {
return supplier;
}
/**
* Gets a result, allow throwing any kind of {@link Exception}.
*
*
* As this hides exceptions from the compiler, the calling method should either:
*
* - have a {@code throws} statement for the hidden exceptions
*
- handle hidden exceptions using {@code catch}
*
- or at least document the hidden exceptions in JavaDoc using
* {@code @throws}.
*
*
* @return a result
* @throws SneakyException hidden exceptions
*/
@Nullable
@Override
@SuppressWarnings({ "checkstyle:IllegalCatch", "PMD.AvoidCatchingGenericException" })
default T get() {
try {
return getThrowing();
} catch (final Exception e) {
throw new SneakyException(e);
}
}
/**
* Gets a result, allow throwing any kind of {@link Exception}.
*
* @return a result
* @throws Exception any kind of exception
*/
@Nullable
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
T getThrowing() throws Exception;
}