502. Java 反射 - 编写 MessageInterceptor 类
1. 设计思路
拦截器的目标是:
- 在调用目标方法前 → 校验或修改参数。
- 调用目标方法 → 执行实际的业务逻辑。
- 在调用目标方法后 → 处理返回值或执行额外逻辑。
在这个例子中,我们希望拦截 SomeInterceptedService.message() 方法,并且:
- 检查参数是否合法(非空、非空字符串)。
- 调用原始方法,获取结果。
- 在结果末尾加上
" [was intercepted]"来表明它被拦截过。
2. MessageInterceptor 实现
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. 示例讲解
原始服务类
public class SomeInterceptedService {
@Intercept(MessageInterceptor.class)
public String message(String input) {
return input.toUpperCase();
}
}
测试调用
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);
}
}
输出结果
Final output = HELLO [was intercepted]
4. 总结
-
参数校验:如果传入
null或空字符串,会抛出异常,阻止目标方法的执行。 -
拦截逻辑:我们在调用
message()前后加入了额外逻辑(参数校验 + 结果追加说明)。 -
反射调用:通过
interceptedMethod.invoke(service, arguments)来执行实际的业务方法。 -
增强返回值:返回值被拦截器修改,增加了
" [was intercepted]"。