Skip to content

Instantly share code, notes, and snippets.

@hellokaton
Last active May 12, 2018 10:49
Show Gist options
  • Save hellokaton/4014be8146b719c9a6898340f61eb3da to your computer and use it in GitHub Desktop.
Save hellokaton/4014be8146b719c9a6898340f61eb3da to your computer and use it in GitHub Desktop.
import java.util.function.Function;
/**
* @author biezhi
* @date 2018/5/12
*/
public class Demo {
public Function<String, Class> loader() {
return Unchecked.function(Class::forName);
}
public void testWrap(){
Unchecked.wrap(() -> {
throw new Exception("我是一个硬生生的 bug.");
});
}
}
import java.util.function.Function;
/**
* 非受检异常工具类
*
* @author biezhi
* @date 2018/5/12
*/
public final class Unchecked {
@FunctionalInterface
interface CheckedFunction<T, R, EX extends Exception> {
R apply(T element) throws EX;
}
@FunctionalInterface
interface NoArgFn<T> {
T apply() throws Exception;
}
public static <T, R> Function<T, R> function(CheckedFunction<T, R, Exception> function) {
return element -> {
try {
return function.apply(element);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
};
}
public static <T> T wrap(NoArgFn<T> f){
try {
return f.apply();
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment