1. 程式人生 > >Java:用Lambda表達式簡化代碼一例

Java:用Lambda表達式簡化代碼一例

得到 ror cep ring false stat bst mex log

  之前,調用第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的過程中,既有驚喜,也有失望。以後會繼續來分享心得。

Java:用Lambda表達式簡化代碼一例