Skip to content

Instantly share code, notes, and snippets.

@kokumura
Created October 29, 2015 07:34
Show Gist options
  • Save kokumura/cd88320ee9d667ef8e46 to your computer and use it in GitHub Desktop.
Save kokumura/cd88320ee9d667ef8e46 to your computer and use it in GitHub Desktop.
Java8のラムダ式でチェック例外を投げられないのを何とかするやつ
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
final public class UnsafeLambdaUtil {
private UnsafeLambdaUtil(){}
public static class ExceptionWrapper extends RuntimeException {
private static final long serialVersionUID = 1L;
public ExceptionWrapper(Exception e){
super(e);
}
}
public static interface UnsafeRunnable{
public void run() throws Exception;
}
public static Runnable wrapr(UnsafeRunnable target){
return (() -> {
try {
target.run();
} catch (Exception e) {
throw wrapException(e);
}
});
}
public static interface UnsafeConsumer<T>{
public void accept(T t) throws Exception;
}
public static <T> Consumer<T> wrapc(UnsafeConsumer<T> target){
return (param -> {
try {
target.accept(param);
} catch (Exception e) {
throw wrapException(e);
}
});
}
public static interface UnsafeSupplier<T>{
public T get() throws Exception;
}
public static <T> Supplier<T> wraps(UnsafeSupplier<T> target){
return (() -> {
try {
return target.get();
} catch (Exception e) {
throw wrapException(e);
}
});
}
public static interface UnsafeFunction<T,R>{
public R apply(T arg) throws Exception;
}
public static <T,R> Function<T,R> wrapf(UnsafeFunction<T,R> target){
return (arg -> {
try {
return target.apply(arg);
} catch (Exception e) {
throw wrapException(e);
}
});
}
public static RuntimeException wrapException(Exception e){
return new ExceptionWrapper(e);
}
}
@kokumura
Copy link
Author

課題

  • ToIntFunctionなどのプリミティブ関数型には対応してないのでmapInt()などの引数には使えない。
  • 例外処理が型安全じゃない
  • ダサい

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment