函数式接口是JDK8的一个非常重要新特性,使用起来可以极大的简化代码。函数式接口(FunctionalInterfac就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。函数式接口可以被隐式转换为lambda表达式。
四大函数式接口
消费型接口:Consumer供给型接口:Supplier函数型接口:Function断言型接口:Predicate
处理异常
定义函数
/**
* 异常处理接口
**/
@FunctionalInterface
public interface ExHandler {
/**
* 异常处理
*
* @param message 异常信息
* @return void
**/
void throwMessage(String message);
}
编写判断方法
/**
* 如果参数为 true 则抛出异常
*
* @param param 参数
* @return com.cloudansys.test.WlfUtil.ExHandler
**/
public static ExHandler isTrue(boolean param) {
return (errorMessage) -> {
if (param) {
throw new RuntimeException(errorMessage);
}
};
}
使用方式
@Test
public void test1() {
WlfUtil.isTrue(false).throwMessage('wlf产生异常');
}
处理null
定义函数
/**
* null 处理接口
*/
@FunctionalInterface
public interface NullHandler {
/**
* null 处理
*
* @param action null 时执行消费操作
* @param nullAction 非 null 时执行其他的操作
* @return void
**/
void handle(Consumer super T> action, Runnable nullAction);
}
编写判断方法
/**
* 参数为 true 或 false 时,分别进行不同的操作
*
* @param param 参数
* @return com.cloudansys.test.WlfUtil.NullHandler
**/
public static NullHandler> isNull(String param) {
return (consumer, runnable) -> {
if (null == param) {
runnable.run();
} else {
consumer.accept(param);
}
};
}
使用方式
@Test
public void test2() {
WlfUtil.isTorF(true).handle(() -> {
System.out.println('是wlf');
}, () -> {
System.out.println('不是wlf');
});
}
处理if
定义函数
/**
* if 处理接口
**/
@FunctionalInterface
public interface IfHandler {
/**
* if 处理
*
* @param trueHandler 为true时要进行的操作
* @param falseHandler 为false时要进行的操作
* @return void
**/
void handle(Runnable trueHandler, Runnable falseHandler);
}
编写判断方法
/**
* 参数为 true 或 false 时,分别进行不同的操作
*
* @param param 参数
* @return com.cloudansys.test.WlfUtil.IfHandler
**/
public static IfHandler isTorF(boolean param) {
return (trueHandle, falseHandle) -> {
if (param) {
trueHandle.run();
} else {
falseHandle.run();
}
};
}
使用方式
@Test
public void test3() {
WlfUtil.isNull(null).handle(System.out::println, () -> {
System.out.println('wlf是null');
});
}
文章为作者独立观点,不代表 股票程序化软件自动交易接口观点