Created
November 8, 2015 00:28
-
-
Save dotStart/883a60560350f4de7b40 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Creates a "sneaky" consumer which disguises all thrown exceptions to work around Javac's checked exceptions. | |
* | |
* @param consumer the sneaky consumer. | |
* @param <I> the input type. | |
* @return the consumer. | |
*/ | |
@Nonnull | |
public static <I> Consumer<I> sneakyConsumer(@Nonnull final SneakyConsumer<I> consumer) { | |
return (i) -> { | |
try { | |
consumer.apply(i); | |
} catch (Exception ex) { | |
Hack.sneakyThrow(ex); | |
} | |
}; | |
} | |
/** | |
* Creates a "sneaky" supplier which disguises all thrown exceptions to work around Javac's checked exceptions. | |
* | |
* @param supplier the sneaky supplier. | |
* @param <O> the output type. | |
* @return the supplier. | |
*/ | |
@Nonnull | |
public static <O> Supplier<O> sneakySupplier(@Nonnull final SneakySupplier<O> supplier) { | |
return () -> { | |
try { | |
return supplier.get(); | |
} catch (Exception ex) { | |
Hack.sneakyThrow(ex); | |
return null; // Makes Javac happy but never occurs | |
} | |
}; | |
} | |
/** | |
* Hides an exception from the Java compiler. | |
* | |
* @param ex the exception. | |
*/ | |
public static void sneakyThrow(@Nonnull final Exception ex) { | |
Hack.<RuntimeException>sneakyThrowInternal(ex); | |
} | |
/** | |
* Hides exceptions from the Java compiler. | |
* | |
* @param ex the exception. | |
* @param <E> the exception type to disguise as. | |
* @throws E the exception you literally just passed you stupid pleb. | |
*/ | |
@SuppressWarnings("unchecked") | |
private static <E extends Exception> void sneakyThrowInternal(@Nonnull final Exception ex) throws E { | |
throw ((E) ex); | |
} | |
/** | |
* Provides a helper interface for replacing consumers with versions that do allow throwing exceptions. | |
* | |
* @param <I> the input type. | |
*/ | |
@FunctionalInterface | |
public interface SneakyConsumer<I> { | |
void apply(@Nonnull I input) throws Exception; | |
} | |
/** | |
* Provides a helper interface for replacing suppliers with versions that do allow throwing exceptions. | |
* | |
* @param <O> the output type. | |
*/ | |
@FunctionalInterface | |
public interface SneakySupplier<O> { | |
@Nonnull | |
O get() throws Exception; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment