Created
October 29, 2015 07:34
-
-
Save kokumura/cd88320ee9d667ef8e46 to your computer and use it in GitHub Desktop.
Java8のラムダ式でチェック例外を投げられないのを何とかするやつ
This file contains 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
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); | |
} | |
} |
課題
- ToIntFunctionなどのプリミティブ関数型には対応してないのでmapInt()などの引数には使えない。
- 例外処理が型安全じゃない
- ダサい
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
このように使う
wrapf, wrapc, wraps, wrapr と名前を変えているのは、同じ名前にすると型推定に失敗したため。