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

后来发现以上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泛型是进阶高级开发必备技能之一,了解实现泛型的基本原理,有助于写出更优质的代码。众所周知,Java是伪泛型,是通过类型擦除(Type Erasure)来实现的。为了̶ ...