Function 函數式接口初識
使用注解@FunctionalInterface標識,並且只包含一個抽象方法的接口是函數式接口。函數式接口主要分為Supplier供給型函數、Consumer消費型函數、Runnable無參無返回型函數和Function有參有返回型函數。
1.代碼示例
@FunctionalInterface public interface BranchHandle { void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle); }
public class VUtils { public static ThrowExceptionFunction isTure(boolean b){ return (errorMessage) ->{ if(b){ throw new RuntimeException(errorMessage); } }; } public static BranchHandle isTureOrFalse(boolean b){ return (trueHandle, falseHandle) -> { if (b){ trueHandle.run(); } else { falseHandle.run(); } }; } }
VUtils.isTureOrFalse(false).trueOrFalseHandle(() -> { System.out.println("true handler ...."); }, () -> { System.out.println("false handler ...."); });
