I know how to create a reference to a method that has a String
parameter and returns an int
, it\'s:
Function
I use an overloaded utility function called unchecked()
which handles multiple use-cases.
SOME EAMPLE USAGES
unchecked(() -> new File("hello.txt").createNewFile());
boolean fileWasCreated = unchecked(() -> new File("hello.txt").createNewFile());
myFiles.forEach(unchecked(file -> new File(file.path).createNewFile()));
SUPPORTING UTILITIES
public class UncheckedUtils {
@FunctionalInterface
public interface ThrowingConsumer {
void accept(T t) throws Exception;
}
@FunctionalInterface
public interface ThrowingSupplier {
T get() throws Exception;
}
@FunctionalInterface
public interface ThrowingRunnable {
void run() throws Exception;
}
public static Consumer unchecked(
ThrowingConsumer throwingConsumer
) {
return i -> {
try {
throwingConsumer.accept(i);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
public static T unchecked(
ThrowingSupplier throwingSupplier
) {
try {
return throwingSupplier.get();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void unchecked(
ThrowingRunnable throwing
) {
try {
throwing.run();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}