Created
March 16, 2018 22:04
-
-
Save VenkataRaju/5abe22f8652f8fdb4f80bb8c07c5bf6f to your computer and use it in GitHub Desktop.
Throw checked exception without declaring and create useful Stream friendly functional interfaces which throws Exception
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
public class SneakyThrow | |
{ | |
public static RuntimeException uncheckedThrow(Throwable t) | |
{ | |
throw uncheckedThrow0(t); | |
} | |
@SuppressWarnings("unchecked") | |
private static <X extends Throwable> RuntimeException uncheckedThrow0(Throwable t) throws X | |
{ | |
throw (X) t; | |
} | |
public interface CheckedFunction<I, O> | |
{ | |
public O apply(I i) throws Exception; | |
} | |
public static <I, O> Function<I, O> uncheckedFunction(CheckedFunction<I, O> cf) | |
{ | |
return (I i) -> | |
{ | |
try | |
{ | |
return cf.apply(i); | |
} | |
catch (Exception e) | |
{ | |
throw uncheckedThrow(e); | |
} | |
}; | |
} | |
public static void main(String[] args) | |
{ | |
Path[] paths = {}; | |
Stream.of(paths).flatMap(SneakyThrow.uncheckedFunction(Files::lines)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment