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简化代码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot项目保证接口幂等的五种方法

    SpringBoot项目保证接口幂等的五种方法

    在计算机领域中,幂等是指任意一个操作的多次执行总是能获得相同的结果,不会对系统状态产生额外影响,在Java后端开发中,幂等性的实现通常通过确保方法或服务调用的结果具有确定性,本文给大家介绍了SpringBoot项目保证接口幂等的五种方法,需要的朋友可以参考下
    2025-07-07
  • Java中的ArrayList、LinkedList、HashSet等容器详解

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

    这篇文章主要介绍了Java中的ArrayList、LinkedList、HashSet等容器详解,集合表示一组对象,称为其元素,有些集合允许重复元素,而另一些则不允许,有些是有序的,有些是无序的,需要的朋友可以参考下
    2023-08-08
  • Java HashSet集合存储遍历学生对象代码实例

    Java HashSet集合存储遍历学生对象代码实例

    这篇文章主要介绍了Java HashSet集合存储遍历学生对象代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • SpringBoot中使用AOP切面编程实现登录拦截功能

    SpringBoot中使用AOP切面编程实现登录拦截功能

    本文介绍了如何使用AOP切面编程实现Spring Boot中的登录拦截,通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2024-12-12
  • Java打包Jar包后使用脚本执行

    Java打包Jar包后使用脚本执行

    本文详细讲解了Java打包Jar包后使用脚本执行的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-12-12
  • 解读Jvm的内存结构与GC及jvm参数调优

    解读Jvm的内存结构与GC及jvm参数调优

    这篇文章主要介绍了解读Jvm的内存结构与GC及jvm参数调优方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • Springboot 自定义线程池的参数配置最优小结

    Springboot 自定义线程池的参数配置最优小结

    在SpringBoot中配置自定义线程池时,参数的设置需要根据具体的应用场景、系统资源和业务需求来调整,本文就来详细的介绍一下,感兴趣的可以了解一下
    2025-10-10
  • 关于解决iReport4.1.1无法正常启动或者闪退或者JDK8不兼容的问题

    关于解决iReport4.1.1无法正常启动或者闪退或者JDK8不兼容的问题

    在安装使用iReport的过程中遇到一个问题,我的iReport始终不能打开,困扰了我好久。接下来通过本文给大家介绍iReport4.1.1无法正常启动或者闪退或者JDK8不兼容的问题,需要的朋友可以参考下
    2018-09-09
  • java连接数据库知识点总结以及操作应用

    java连接数据库知识点总结以及操作应用

    这篇文章主要给大家介绍了关于java连接数据库知识点总结以及操作应用的相关资料, 当涉及到Java中数据库数据处理时,我们可以利用强大的Java数据库连接技术与各种数据库进行交互,需要的朋友可以参考下
    2023-12-12
  • Java源码刨析之ArrayDeque

    Java源码刨析之ArrayDeque

    ArrayDeque是Deque接口的一个实现,使用了可变数组,所以没有容量上的限制。同时, ArrayDeque是线程不安全的,在没有外部同步的情况下,不能再多线程环境下使用<BR>
    2022-07-07

最新评论