Java通過(guò)Lambda表達(dá)式實(shí)現(xiàn)簡(jiǎn)化代碼
之前,調(diào)用第3方服務(wù),每個(gè)方法都差不多“長(zhǎng)”這樣, 寫(xiě)起來(lái)啰嗦, 改起來(lái)麻煩, 還容易改漏。
public void authorizeRoleToUser(Long userId, List<Long> roleIds) { try { power.authorizeRoleToUser(userId, roleIds); } catch (MotanCustomException ex) { if (ex.getCode().equals(MSUserException.notLogin().getCode())) throw UserException.notLogin(); if (ex.getCode().equals(MSPowerException.haveNoPower().getCode())) throw PowerException.haveNoPower(); throw ex; } catch (MotanServiceException ex) { CatHelper.logEventService("Power-authorizeRoleToUser", "authorizeRoleToUser", ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (MotanAbstractException ex) { CatHelper.logEventService("Power-authorizeRoleToUser", "authorizeRoleToUser", ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (Exception ex) { CatHelper.logError(ex); throw ex; } }
我經(jīng)過(guò)學(xué)習(xí)和提取封裝, 將try ... catch ... catch .. 提取為公用, 得到這2個(gè)方法:
import java.util.function.Supplier; public static <T> T tryCatch(Supplier<T> supplier, String serviceName, String methodName) { try { return supplier.get(); } catch (MotanCustomException ex) { if (ex.getCode().equals(MSUserException.notLogin().getCode())) throw UserException.notLogin(); if (ex.getCode().equals(MSPowerException.haveNoPower().getCode())) throw PowerException.haveNoPower(); throw ex; } catch (MotanServiceException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (MotanAbstractException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (Exception ex) { CatHelper.logError(ex); throw ex; } } public static void tryCatch(Runnable runnable, String serviceName, String methodName) { tryCatch(() -> { runnable.run(); return null; }, serviceName, methodName); }
現(xiàn)在用起來(lái)是如此簡(jiǎn)潔。像這種無(wú)返回值的:
public void authorizeRoleToUser(Long userId, List<Long> roleIds) { tryCatch(() -> { power.authorizeRoleToUser(userId, roleIds); }, "Power", "authorizeRoleToUser"); }
還有這種有返回值的:
public List<RoleDTO> listRoleByUser(Long userId) { return tryCatch(() -> power.listRoleByUser(userId), "Power", "listRoleByUser"); }
后來(lái)發(fā)現(xiàn)以上2個(gè)方法還不夠用, 原因是有一些方法會(huì)拋出 checked 異常, 于是又再添加了一個(gè)能處理異常的, 這次意外發(fā)現(xiàn)Java的throws也支持泛型, 贊一個(gè):
public static <T, E extends Throwable> T tryCatchException(SupplierException<T, E> supplier, String serviceName, String methodName) throws E { try { return supplier.get(); } catch (MotanCustomException ex) { if (ex.getCode().equals(MSUserException.notLogin().getCode())) throw UserException.notLogin(); if (ex.getCode().equals(MSPowerException.haveNoPower().getCode())) throw PowerException.haveNoPower(); throw ex; } catch (MotanServiceException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (MotanAbstractException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (Exception ex) { CatHelper.logError(ex); throw ex; } } @FunctionalInterface public interface SupplierException<T, E extends Throwable> { /** * Gets a result. * * @return a result */ T get() throws E; }
為了不至于維護(hù)兩份catch集, 將原來(lái)的帶返回值的tryCatch改為調(diào)用tryCatchException:
public static <T> T tryCatch(Supplier<T> supplier, String serviceName, String methodName) { return tryCatchException(() -> supplier.get(), serviceName, methodName); }
這個(gè)世界又完善了一步。
前面制作了3種情況:
1.無(wú)返回值,無(wú) throws
2.有返回值,無(wú) throws
3.有返回值,有 throws
不確定會(huì)不會(huì)出現(xiàn)“無(wú)返回值,有throws“的情況。后來(lái)真的出現(xiàn)了!依樣畫(huà)葫蘆,弄出了這個(gè):
public static <E extends Throwable> void tryCatchException(RunnableException<E> runnable, String serviceName, String methodName) throws E { tryCatchException(() -> { runnable.run(); return null; }, serviceName, methodName); } @FunctionalInterface public interface RunnableException<E extends Throwable> { void run() throws E; }
完整代碼
package com.company.system.util; import java.util.function.Supplier; import org.springframework.beans.factory.BeanCreationException; import com.company.cat.monitor.CatHelper; import com.company.system.customException.PowerException; import com.company.system.customException.ServiceException; import com.company.system.customException.UserException; import com.company.hyhis.ms.user.custom.exception.MSPowerException; import com.company.hyhis.ms.user.custom.exception.MSUserException; import com.company.hyhis.ms.user.custom.exception.MotanCustomException; import com.weibo.api.motan.exception.MotanAbstractException; import com.weibo.api.motan.exception.MotanServiceException; public class ThirdParty { public static void tryCatch(Runnable runnable, String serviceName, String methodName) { tryCatch(() -> { runnable.run(); return null; }, serviceName, methodName); } public static <T> T tryCatch(Supplier<T> supplier, String serviceName, String methodName) { return tryCatchException(() -> supplier.get(), serviceName, methodName); } public static <E extends Throwable> void tryCatchException(RunnableException<E> runnable, String serviceName, String methodName) throws E { tryCatchException(() -> { runnable.run(); return null; }, serviceName, methodName); } public static <T, E extends Throwable> T tryCatchException(SupplierException<T, E> supplier, String serviceName, String methodName) throws E { try { return supplier.get(); } catch (MotanCustomException ex) { if (ex.getCode().equals(MSUserException.notLogin().getCode())) throw UserException.notLogin(); if (ex.getCode().equals(MSPowerException.haveNoPower().getCode())) throw PowerException.haveNoPower(); throw ex; } catch (MotanServiceException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (MotanAbstractException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (Exception ex) { CatHelper.logError(ex); throw ex; } } @FunctionalInterface public interface RunnableException<E extends Throwable> { void run() throws E; } @FunctionalInterface public interface SupplierException<T, E extends Throwable> { T get() throws E; } }
到此這篇關(guān)于Java通過(guò)Lambda表達(dá)式實(shí)現(xiàn)簡(jiǎn)化代碼的文章就介紹到這了,更多相關(guān)Java簡(jiǎn)化代碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java數(shù)據(jù)庫(kù)連接池之DBCP淺析_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了Java數(shù)據(jù)庫(kù)連接池之DBCP的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn)
這篇文章主要介紹了JAVA Iterator接口與增強(qiáng)for循環(huán)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11Java8實(shí)戰(zhàn)之Stream的延遲計(jì)算
JDK中Stream的中間函數(shù)如 filter(Predicate super T>)是惰性求值的,filter并非對(duì)流中所有元素調(diào)用傳遞給它的Predicate,下面這篇文章主要給大家介紹了關(guān)于Java8實(shí)戰(zhàn)之Stream延遲計(jì)算的相關(guān)資料,需要的朋友可以參考下2021-09-09詳細(xì)介紹idea如何設(shè)置類(lèi)頭注釋和方法注釋(圖文)
本篇文章主要介紹了idea如何設(shè)置類(lèi)頭注釋和方法注釋(圖文),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-12-12Java 比較接口comparable與comparator區(qū)別解析
這篇文章主要介紹了Java 比較接口comparable與comparator區(qū)別解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10數(shù)據(jù)庫(kù)連接超時(shí)java處理的兩種方式
這篇文章主要介紹了數(shù)據(jù)庫(kù)連接超時(shí)java處理的兩種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04