CheckedSupplier action 这种参数本质上是“一个会返回 String、但允许抛出受检异常的函数”一般用在想把“可能会抛异常的代码块”作为参数传进去统一处理的场景。下面从「是什么 → 常见用法 → 实战例子」一步步说清楚。一、CheckedSupplier 是什么1️⃣ 标准 JDK 没有 CheckedSupplierJDK 自带的是FunctionalInterfacepublic interface Supplier {T get(); // ❌ 不能抛受检异常}而 CheckedSupplier 通常是自定义或工具库提供的比如FunctionalInterfacepublic interface CheckedSupplier {T get() throws Exception;}✅ 唯一的区别get() 允许 throws Exception二、为什么要用 CheckedSupplier核心动机把“可能失败的代码”当成参数传进去由调用方统一处理异常、重试、超时、日志等。否则你会写成这样重复代码try {doA();} catch (Exception e) {log.error(…);}try {doB();} catch (Exception e) {log.error(…);}用 CheckedSupplier 可以统一成run(action);三、最典型的 5 种用法✅ 1️⃣ 统一异常处理最常见public String run(CheckedSupplier supplier) {try {return supplier.get();} catch (Exception e) {log.error(“执行失败”, e);throw new RuntimeException(e);}}调用String result run(() - readFile(“a.txt”));✅ 2️⃣ 重试机制Retrypublic String retry(int times, CheckedSupplier supplier) throws Exception {int i 0;while (true) {try {return supplier.get();} catch (Exception e) {if (i times) throw e;}}}调用String s retry(3, () - callRemoteApi());✅ 3️⃣ 超时控制Timeoutpublic String timeout(Duration duration, CheckedSupplier supplier) {Future future executor.submit(supplier::get);return future.get(duration.toMillis(), TimeUnit.MILLISECONDS);}✅ 4️⃣ 事务 / 资源上下文包装public String inTransaction(CheckedSupplier supplier) {beginTx();try {String r supplier.get();commit();return r;} catch (Exception e) {rollback();throw e;}}✅ 5️⃣ 测试 / Mock / 模板方法public void test(CheckedSupplier action) {setup();String r action.get();verify®;}四、和常见接口对比接口 返回值 能否抛受检异常Supplier T ❌Callable T ✅CheckedSupplier T ✅Runnable void ❌✅ 所以• 只想“执行一段代码” → Runnable• 要返回值 允许异常 → CheckedSupplier / Callable五、真实项目中的常见形态Spring / 工具类中常见写法public static T executeWithLog(CheckedSupplier supplier) {long start System.currentTimeMillis();try {return supplier.get();} catch (Exception e) {log.error(“执行异常”, e);throw new RuntimeException(e);} finally {log.info(“耗时{}”, System.currentTimeMillis() - start);}}六、什么时候不该用❌ 业务逻辑本身很简单❌ 不需要统一处理异常 / 重试 / 超时✅ 否则会 过度抽象、可读性变差✅ 一句话总结CheckedSupplier action 一个“会返回 String、但可能抛异常的任务”通常用来做 统一异常处理、重试、超时、事务、监控、模板方法。