zoukankan      html  css  js  c++  java
  • Java:用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");
    }
    

      这是我的第一篇Java文章。学习Java的过程中,既有惊喜,也有失望。以后会继续来分享心得。

    --------------我是分隔线---------------

    后来发现以上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);
    }

    这个世界又完善了一步。

    ---------------我是第2条分隔线--------------------

    前面制作了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;
    }

      现在,”人齐了“,拍张全家福:

     1 package com.company.system.util;
     2 
     3 import java.util.function.Supplier;
     4 
     5 import org.springframework.beans.factory.BeanCreationException;
     6 
     7 import com.company.cat.monitor.CatHelper;
     8 import com.company.system.customException.PowerException;
     9 import com.company.system.customException.ServiceException;
    10 import com.company.system.customException.UserException;
    11 import com.company.hyhis.ms.user.custom.exception.MSPowerException;
    12 import com.company.hyhis.ms.user.custom.exception.MSUserException;
    13 import com.company.hyhis.ms.user.custom.exception.MotanCustomException;
    14 import com.weibo.api.motan.exception.MotanAbstractException;
    15 import com.weibo.api.motan.exception.MotanServiceException;
    16 
    17 public class ThirdParty {
    18 
    19     public static void tryCatch(Runnable runnable, String serviceName, String methodName) {
    20         tryCatch(() -> {
    21             runnable.run();
    22             return null;
    23         }, serviceName, methodName);
    24     }
    25 
    26     public static <T> T tryCatch(Supplier<T> supplier, String serviceName, String methodName) {
    27         return tryCatchException(() -> supplier.get(), serviceName, methodName);
    28     }
    29 
    30     public static <E extends Throwable> void tryCatchException(RunnableException<E> runnable, String serviceName,
    31             String methodName) throws E {
    32         tryCatchException(() -> {
    33             runnable.run();
    34             return null;
    35         }, serviceName, methodName);
    36     }
    37 
    38     public static <T, E extends Throwable> T tryCatchException(SupplierException<T, E> supplier, String serviceName,
    39             String methodName) throws E {
    40         try {
    41             return supplier.get();
    42         } catch (MotanCustomException ex) {
    43             if (ex.getCode().equals(MSUserException.notLogin().getCode()))
    44                 throw UserException.notLogin();
    45             if (ex.getCode().equals(MSPowerException.haveNoPower().getCode()))
    46                 throw PowerException.haveNoPower();
    47             throw ex;
    48         } catch (MotanServiceException ex) {
    49             CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(),
    50                     ex.getMessage());
    51             throw ex;
    52         } catch (MotanAbstractException ex) {
    53             CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(),
    54                     ex.getMessage());
    55             throw ex;
    56         } catch (Exception ex) {
    57             CatHelper.logError(ex);
    58             throw ex;
    59         }
    60     }
    61 
    62     @FunctionalInterface
    63     public interface RunnableException<E extends Throwable> {
    64         void run() throws E;
    65     }
    66 
    67     @FunctionalInterface
    68     public interface SupplierException<T, E extends Throwable> {
    69         T get() throws E;
    70     }
    71 }
    View Code
  • 相关阅读:
    初识Tensorboard
    sql优化的几种方法
    nginx+ffmpeg+jwplayer
    jwplayer播放器
    详解spring 每个jar的作用
    RabbitMQ安装
    Migration 使用方法
    VisualSVN server 启用日志编辑
    nodejs prefix(全局)和cache(缓存)windows下设置
    python3 eval字符串str 转字典dict
  • 原文地址:https://www.cnblogs.com/BillySir/p/7494090.html
Copyright © 2011-2022 走看看