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 }
博主简介:佘焕敏(shé),洋名 Billy Sir。
关注编程基础技术,并致力于研究软件的自动化生成。 对编程规范化、面向对象的极致使用也有着浓厚的兴趣。 同时非常希望能够写程序到65岁。
只有工匠精神,才能把常人觉得单调乏味的代码,当作作品雕刻成艺术品。
重点:这里几乎每一篇文章,都是我认真创作的,凝结了心血。写作从来都不是一件容易的事,对从小语文不好的我而言,是难上加难。而且,你发现没有,文中没有广告。这篇文章介绍了为什么要写这些文章。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南