最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java通過(guò)Lambda表達(dá)式實(shí)現(xiàn)簡(jiǎn)化代碼

 更新時(shí)間:2023年05月22日 15:21:26   作者:BillySir  
我們?cè)诰帉?xiě)代碼時(shí),常常會(huì)遇到代碼又長(zhǎng)又重復(fù)的情況,就像調(diào)用第3方服務(wù)時(shí),每個(gè)方法都差不多,?寫(xiě)起來(lái)啰嗦,?改起來(lái)麻煩,?還容易改漏,所以本文就來(lái)用Lambda表達(dá)式簡(jiǎn)化一下代碼,希望對(duì)大家有所幫助

之前,調(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)文章

  • SpringBoot項(xiàng)目保證接口冪等的五種方法

    SpringBoot項(xiàng)目保證接口冪等的五種方法

    在計(jì)算機(jī)領(lǐng)域中,冪等是指任意一個(gè)操作的多次執(zhí)行總是能獲得相同的結(jié)果,不會(huì)對(duì)系統(tǒng)狀態(tài)產(chǎn)生額外影響,在Java后端開(kāi)發(fā)中,冪等性的實(shí)現(xiàn)通常通過(guò)確保方法或服務(wù)調(diào)用的結(jié)果具有確定性,本文給大家介紹了SpringBoot項(xiàng)目保證接口冪等的五種方法,需要的朋友可以參考下
    2025-07-07
  • Java中的ArrayList、LinkedList、HashSet等容器詳解

    Java中的ArrayList、LinkedList、HashSet等容器詳解

    這篇文章主要介紹了Java中的ArrayList、LinkedList、HashSet等容器詳解,集合表示一組對(duì)象,稱為其元素,有些集合允許重復(fù)元素,而另一些則不允許,有些是有序的,有些是無(wú)序的,需要的朋友可以參考下
    2023-08-08
  • Java HashSet集合存儲(chǔ)遍歷學(xué)生對(duì)象代碼實(shí)例

    Java HashSet集合存儲(chǔ)遍歷學(xué)生對(duì)象代碼實(shí)例

    這篇文章主要介紹了Java HashSet集合存儲(chǔ)遍歷學(xué)生對(duì)象代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-04-04
  • SpringBoot中使用AOP切面編程實(shí)現(xiàn)登錄攔截功能

    SpringBoot中使用AOP切面編程實(shí)現(xiàn)登錄攔截功能

    本文介紹了如何使用AOP切面編程實(shí)現(xiàn)Spring Boot中的登錄攔截,通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧
    2024-12-12
  • Java打包Jar包后使用腳本執(zhí)行

    Java打包Jar包后使用腳本執(zhí)行

    本文詳細(xì)講解了Java打包Jar包后使用腳本執(zhí)行的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-12-12
  • 解讀Jvm的內(nèi)存結(jié)構(gòu)與GC及jvm參數(shù)調(diào)優(yōu)

    解讀Jvm的內(nèi)存結(jié)構(gòu)與GC及jvm參數(shù)調(diào)優(yōu)

    這篇文章主要介紹了解讀Jvm的內(nèi)存結(jié)構(gòu)與GC及jvm參數(shù)調(diào)優(yōu)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • Springboot 自定義線程池的參數(shù)配置最優(yōu)小結(jié)

    Springboot 自定義線程池的參數(shù)配置最優(yōu)小結(jié)

    在SpringBoot中配置自定義線程池時(shí),參數(shù)的設(shè)置需要根據(jù)具體的應(yīng)用場(chǎng)景、系統(tǒng)資源和業(yè)務(wù)需求來(lái)調(diào)整,本文就來(lái)詳細(xì)的介紹一下,感興趣的可以了解一下
    2025-10-10
  • 關(guān)于解決iReport4.1.1無(wú)法正常啟動(dòng)或者閃退或者JDK8不兼容的問(wèn)題

    關(guān)于解決iReport4.1.1無(wú)法正常啟動(dòng)或者閃退或者JDK8不兼容的問(wèn)題

    在安裝使用iReport的過(guò)程中遇到一個(gè)問(wèn)題,我的iReport始終不能打開(kāi),困擾了我好久。接下來(lái)通過(guò)本文給大家介紹iReport4.1.1無(wú)法正常啟動(dòng)或者閃退或者JDK8不兼容的問(wèn)題,需要的朋友可以參考下
    2018-09-09
  • java連接數(shù)據(jù)庫(kù)知識(shí)點(diǎn)總結(jié)以及操作應(yīng)用

    java連接數(shù)據(jù)庫(kù)知識(shí)點(diǎn)總結(jié)以及操作應(yīng)用

    這篇文章主要給大家介紹了關(guān)于java連接數(shù)據(jù)庫(kù)知識(shí)點(diǎn)總結(jié)以及操作應(yīng)用的相關(guān)資料, 當(dāng)涉及到Java中數(shù)據(jù)庫(kù)數(shù)據(jù)處理時(shí),我們可以利用強(qiáng)大的Java數(shù)據(jù)庫(kù)連接技術(shù)與各種數(shù)據(jù)庫(kù)進(jìn)行交互,需要的朋友可以參考下
    2023-12-12
  • Java源碼刨析之ArrayDeque

    Java源碼刨析之ArrayDeque

    ArrayDeque是Deque接口的一個(gè)實(shí)現(xiàn),使用了可變數(shù)組,所以沒(méi)有容量上的限制。同時(shí),?ArrayDeque是線程不安全的,在沒(méi)有外部同步的情況下,不能再多線程環(huán)境下使用<BR>
    2022-07-07

最新評(píng)論

庄浪县| 忻州市| 攀枝花市| 缙云县| 藁城市| 饶阳县| 祁阳县| 新巴尔虎左旗| 尼勒克县| 宁海县| 府谷县| 五大连池市| 五寨县| 宁晋县| 怀远县| 靖远县| 二连浩特市| 怀来县| 高陵县| 陇西县| 石棉县| 东丰县| 出国| 思茅市| 华蓥市| 紫金县| 海伦市| 化州市| 平阳县| 昭苏县| 湛江市| 南皮县| 酒泉市| 孝义市| 绍兴县| 道孚县| 尖扎县| 临桂县| 自治县| 湟中县| 柳林县|