502. Java 反射 - 编写 MessageInterceptor 类

文章目录

  • [502. Java 反射 - 编写 MessageInterceptor 类](#502. Java 反射 - 编写 MessageInterceptor 类)
    • [1. 设计思路](#1. 设计思路)
    • [2. MessageInterceptor 实现](#2. MessageInterceptor 实现)
    • [3. 示例讲解](#3. 示例讲解)
    • [4. 总结](#4. 总结)

502. Java 反射 - 编写 MessageInterceptor 类

1. 设计思路

拦截器的目标是:

  1. 在调用目标方法前 → 校验或修改参数。
  2. 调用目标方法 → 执行实际的业务逻辑。
  3. 在调用目标方法后 → 处理返回值或执行额外逻辑。

在这个例子中,我们希望拦截 SomeInterceptedService.message() 方法,并且:

  • 检查参数是否合法(非空、非空字符串)。
  • 调用原始方法,获取结果。
  • 在结果末尾加上 " [was intercepted]" 来表明它被拦截过。

2. MessageInterceptor 实现

java 复制代码
public class MessageInterceptor implements Interceptor<SomeInterceptedService, String> {

    @Override
    public String intercept(
            SomeInterceptedService service, Method interceptedMethod, Object... arguments) {
        try {
            if (arguments.length == 1) {

                // ✅ 1. 参数校验
                String input = (String) arguments[0];
                Objects.requireNonNull(input, "Input is null");
                if (input.isEmpty()) {
                    throw new IllegalArgumentException("Input is empty");
                }

                // ✅ 2. 调用目标方法
                String result = (String) interceptedMethod.invoke(service, arguments);

                // ✅ 3. 修改返回值
                return result + " [was intercepted]";
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException("Error invoking method reflectively", e);
        }

        throw new IllegalArgumentException(
                "Arguments should contain exactly one argument of type String");
    }
}

3. 示例讲解

原始服务类

java 复制代码
public class SomeInterceptedService {
    @Intercept(MessageInterceptor.class)
    public String message(String input) {
        return input.toUpperCase();
    }
}

测试调用

java 复制代码
public class Main {
    public static void main(String[] args) throws Exception {
        String output = (String) ServiceFactory.invoke(SomeInterceptedService.class, "message", "hello");
        System.out.println("Final output = " + output);
    }
}

输出结果

java 复制代码
Final output = HELLO [was intercepted]

4. 总结

  • 参数校验 :如果传入 null 或空字符串,会抛出异常,阻止目标方法的执行。
  • 拦截逻辑 :我们在调用 message() 前后加入了额外逻辑(参数校验 + 结果追加说明)。
  • 反射调用 :通过 interceptedMethod.invoke(service, arguments) 来执行实际的业务方法。
  • 增强返回值 :返回值被拦截器修改,增加了 " [was intercepted]"
相关推荐
wuyk5551 小时前
Python零基础入门第五章:元组Tuple(不可变容器详解、列表与元组区别)
开发语言·python
风流 少年1 小时前
Spring AI 2.0:阿里云百炼平台(工作流应用)
java·后端·spring
长谷深风1111 小时前
AI Tool 设计:粒度、参数与错误恢复怎么做
java·大数据·人工智能·ai agent·agent工作流·智能体设计·ai产品设计
2601_965798471 小时前
Build a Fast, High-Ranking Restaurant Website with Rolanda Theme
开发语言·ios·swift
caimouse1 小时前
ReactOS 窗口系统分析(25):标题栏显示与系统按钮 — nonclient.c 标题栏专题
c语言·开发语言
诺伦1 小时前
Rust 错误处理实战:从 unwrap 到优雅 Result 的进阶之路
开发语言·后端·rust
caimouse2 小时前
ReactOS 窗口系统分析(14):计时器/属性/加速键/热键 — timer.c + prop.c + accelerator.c + hotkey.c
c语言·开发语言·reactos
circuitsosk2 小时前
Python 模块与包管理:import 机制、虚拟环境与 pip 完全指南
开发语言·python·pip·依赖管理·模块与包
就叫飞六吧2 小时前
两道门:X-Frame-Options 和 SameSite 到底谁管什么
开发语言·chrome·ai编程