亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java通過Lambda表達(dá)式實現(xiàn)簡化代碼

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

之前,調(diào)用第3方服務(wù),每個方法都差不多“長”這樣, 寫起來啰嗦, 改起來麻煩, 還容易改漏。

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)過學(xué)習(xí)和提取封裝, 將try ... catch ... catch .. 提取為公用, 得到這2個方法:

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)在用起來是如此簡潔。像這種無返回值的:

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");
}

后來發(fā)現(xiàn)以上2個方法還不夠用, 原因是有一些方法會拋出 checked 異常, 于是又再添加了一個能處理異常的, 這次意外發(fā)現(xiàn)Java的throws也支持泛型, 贊一個:

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集, 將原來的帶返回值的tryCatch改為調(diào)用tryCatchException:

public static <T> T tryCatch(Supplier<T> supplier, String serviceName, String methodName) {
    return tryCatchException(() -> supplier.get(), serviceName, methodName);
}

這個世界又完善了一步。

前面制作了3種情況:

1.無返回值,無 throws

2.有返回值,無 throws

3.有返回值,有 throws

不確定會不會出現(xiàn)“無返回值,有throws“的情況。后來真的出現(xiàn)了!依樣畫葫蘆,弄出了這個:

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通過Lambda表達(dá)式實現(xiàn)簡化代碼的文章就介紹到這了,更多相關(guān)Java簡化代碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java數(shù)據(jù)庫連接池之DBCP淺析_動力節(jié)點(diǎn)Java學(xué)院整理

    Java數(shù)據(jù)庫連接池之DBCP淺析_動力節(jié)點(diǎn)Java學(xué)院整理

    這篇文章主要為大家詳細(xì)介紹了Java數(shù)據(jù)庫連接池之DBCP的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-08-08
  • echarts圖表導(dǎo)出excel示例

    echarts圖表導(dǎo)出excel示例

    這篇文章主要介紹了echarts圖表導(dǎo)出excel示例,需要的朋友可以參考下
    2014-04-04
  • JAVA Iterator接口與增強(qiáng)for循環(huán)的實現(xiàn)

    JAVA Iterator接口與增強(qiáng)for循環(huán)的實現(xiàn)

    這篇文章主要介紹了JAVA Iterator接口與增強(qiáng)for循環(huán)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-11-11
  • Java代碼讀取properties配置文件的示例代碼

    Java代碼讀取properties配置文件的示例代碼

    這篇文章主要介紹了Java代碼讀取properties配置文件,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-05-05
  • Java8實戰(zhàn)之Stream的延遲計算

    Java8實戰(zhàn)之Stream的延遲計算

    JDK中Stream的中間函數(shù)如 filter(Predicate super T>)是惰性求值的,filter并非對流中所有元素調(diào)用傳遞給它的Predicate,下面這篇文章主要給大家介紹了關(guān)于Java8實戰(zhàn)之Stream延遲計算的相關(guān)資料,需要的朋友可以參考下
    2021-09-09
  • 詳細(xì)介紹idea如何設(shè)置類頭注釋和方法注釋(圖文)

    詳細(xì)介紹idea如何設(shè)置類頭注釋和方法注釋(圖文)

    本篇文章主要介紹了idea如何設(shè)置類頭注釋和方法注釋(圖文),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-12-12
  • Java 比較接口comparable與comparator區(qū)別解析

    Java 比較接口comparable與comparator區(qū)別解析

    這篇文章主要介紹了Java 比較接口comparable與comparator區(qū)別解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-10-10
  • Java基礎(chǔ)-封裝和繼承

    Java基礎(chǔ)-封裝和繼承

    這篇文章主要介紹了Java面向?qū)ο缶幊蹋ǚ庋b/繼承/多態(tài))實例解析的相關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下希望可以幫助到你
    2021-07-07
  • 數(shù)據(jù)庫連接超時java處理的兩種方式

    數(shù)據(jù)庫連接超時java處理的兩種方式

    這篇文章主要介紹了數(shù)據(jù)庫連接超時java處理的兩種方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • Java圖片壓縮三種高效壓縮方案詳細(xì)解析

    Java圖片壓縮三種高效壓縮方案詳細(xì)解析

    圖片壓縮通常涉及減少圖片的尺寸縮放、調(diào)整圖片的質(zhì)量(針對JPEG、PNG等)、使用特定的算法來減少圖片的數(shù)據(jù)量等,這篇文章主要介紹了Java圖片壓縮三種高效壓縮方案的相關(guān)資料,需要的朋友可以參考下
    2025-04-04

最新評論