妙用Java 8中的 Function接口 消滅if...else(非常新穎的寫法)
閱讀本文大概需要 3 分鐘。
來自:juejin.cn/post/7011435192803917831
if (...){throw new RuntimeException("出現(xiàn)異常了");}if (...){doSomething();} else {doOther();}
Function可以看作轉(zhuǎn)換型函數(shù)




/*** 拋異常接口**/@FunctionalInterfacepublic interface ThrowExceptionFunction {/*** 拋出異常信息** @param message 異常信息* @return void**/void throwMessage(String message);}
/*** 如果參數(shù)為true拋出異常** @param b* @return com.example.demo.func.ThrowExceptionFunction**/public static ThrowExceptionFunction isTure(boolean b){return (errorMessage) -> {if (b){throw new RuntimeException(errorMessage);}};}


/*** 分支處理接口**/@FunctionalInterfacepublic interface BranchHandle {/*** 分支操作** @param trueHandle 為true時要進行的操作* @param falseHandle 為false時要進行的操作* @return void**/void trueOrFalseHandle(Runnable trueHandle, Runnable falseHandle);}
/*** 參數(shù)為true或false時,分別進行不同的操作** @param b* @return com.example.demo.func.BranchHandle**/public static BranchHandle isTureOrFalse(boolean b){return (trueHandle, falseHandle) -> {if (b){trueHandle.run();} else {falseHandle.run();}};}


/*** 空值與非空值分支處理*/public interface PresentOrElseHandler<T extends Object> {/*** 值不為空時執(zhí)行消費操作* 值為空時執(zhí)行其他的操作** @param action 值不為空時,執(zhí)行的消費操作* @param emptyAction 值為空時,執(zhí)行的操作* @return void**/void presentOrElseHandle(Consumer<? super T> action, Runnable emptyAction);}
/*** 參數(shù)為true或false時,分別進行不同的操作** @param b* @return com.example.demo.func.BranchHandle**/public static PresentOrElseHandler> isBlankOrNoBlank(String str){return (consumer, runnable) -> {if (str == null || str.length() == 0){runnable.run();} else {consumer.accept(str);}};}


推薦閱讀:
心態(tài)崩了!稅前2萬4,到手1萬4,年終獎扣稅方式1月1日起施行~
內(nèi)容包含Java基礎(chǔ)、JavaWeb、MySQL性能優(yōu)化、JVM、鎖、百萬并發(fā)、消息隊列、高性能緩存、反射、Spring全家桶原理、微服務、Zookeeper、數(shù)據(jù)結(jié)構(gòu)、限流熔斷降級......等技術(shù)棧!
?戳閱讀原文領(lǐng)??! 朕已閱 
評論
圖片
表情

