Java通过Lambda表达式实现简化代码

 更新时间:2023年05月22日 15:21:26   作者:BillySir  
我们在编写代码时,常常会遇到代码又长又重复的情况,就像调用第3方服务时,每个方法都差不多, 写起来啰嗦, 改起来麻烦, 还容易改漏,所以本文就来用Lambda表达式简化一下代码,希望对大家有所帮助

之前,调用第3方服务,每个方法都差不多“长”这样, 写起来啰嗦, 改起来麻烦, 还容易改漏。

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

我经过学习和提取封装, 将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);
}

现在用起来是如此简洁。像这种无返回值的:

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

后来发现以上2个方法还不够用, 原因是有一些方法会抛出 checked 异常, 于是又再添加了一个能处理异常的, 这次意外发现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;
}

为了不至于维护两份catch集, 将原来的带返回值的tryCatch改为调用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

不确定会不会出现“无返回值,有throws“的情况。后来真的出现了!依样画葫芦,弄出了这个:

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

到此这篇关于Java通过Lambda表达式实现简化代码的文章就介绍到这了,更多相关Java简化代码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java数据库连接池之DBCP浅析_动力节点Java学院整理

    Java数据库连接池之DBCP浅析_动力节点Java学院整理

    这篇文章主要为大家详细介绍了Java数据库连接池之DBCP的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-08-08
  • echarts图表导出excel示例

    echarts图表导出excel示例

    这篇文章主要介绍了echarts图表导出excel示例,需要的朋友可以参考下
    2014-04-04
  • JAVA Iterator接口与增强for循环的实现

    JAVA Iterator接口与增强for循环的实现

    这篇文章主要介绍了JAVA Iterator接口与增强for循环的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • Java代码读取properties配置文件的示例代码

    Java代码读取properties配置文件的示例代码

    这篇文章主要介绍了Java代码读取properties配置文件,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-05-05
  • Java8实战之Stream的延迟计算

    Java8实战之Stream的延迟计算

    JDK中Stream的中间函数如 filter(Predicate super T>)是惰性求值的,filter并非对流中所有元素调用传递给它的Predicate,下面这篇文章主要给大家介绍了关于Java8实战之Stream延迟计算的相关资料,需要的朋友可以参考下
    2021-09-09
  • 详细介绍idea如何设置类头注释和方法注释(图文)

    详细介绍idea如何设置类头注释和方法注释(图文)

    本篇文章主要介绍了idea如何设置类头注释和方法注释(图文),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • Java 比较接口comparable与comparator区别解析

    Java 比较接口comparable与comparator区别解析

    这篇文章主要介绍了Java 比较接口comparable与comparator区别解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-10-10
  • Java基础-封装和继承

    Java基础-封装和继承

    这篇文章主要介绍了Java面向对象编程(封装/继承/多态)实例解析的相关内容,具有一定参考价值,需要的朋友可以了解下希望可以帮助到你
    2021-07-07
  • 数据库连接超时java处理的两种方式

    数据库连接超时java处理的两种方式

    这篇文章主要介绍了数据库连接超时java处理的两种方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-04-04
  • Java图片压缩三种高效压缩方案详细解析

    Java图片压缩三种高效压缩方案详细解析

    图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,这篇文章主要介绍了Java图片压缩三种高效压缩方案的相关资料,需要的朋友可以参考下
    2025-04-04

最新评论