Java动态代理通过Proxy.newProxyInstance()和InvocationHandler实现接口方法的日志切面,支持方法调用前后耗时统计、异常捕获与返回值处理,但仅限接口代理,不支持类代理。

在 Java 中,用 Proxy.newProxyInstance() 配合 InvocationHandler 实现动态日志切面,核心是拦截目标接口方法调用,在前后插入日志逻辑,无需修改业务代码,也不依赖 Spring AOP。
前提:只能代理接口,不能代理类
Java 原生动态代理仅支持对接口生成代理对象。若目标类没有实现接口,需改写为面向接口编程,或改用 CGLIB(但那是另一套机制)。
例如定义一个服务接口:
public interface UserService {
String getName(int id);
void updateName(int id, String name);
}编写自定义 InvocationHandler 添加日志逻辑
实现 InvocationHandler,在 invoke() 中统一处理方法进入、执行、返回/异常等时机的日志输出:
- 用
method.getName()和args记录入参 - 用
System.nanoTime()或Instant.now()计算耗时 - 捕获异常并记录堆栈,再重新抛出保持原有行为
- 对返回值做简单格式化(如字符串截断、null 处理),避免日志刷屏
public class LoggingInvocationHandler implements InvocationHandler {
private final Object target;
<pre class="brush:php;toolbar:false;">public LoggingInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
System.out.println("[LOG] → " + methodName + "(" + Arrays.toString(args) + ")");
long start = System.nanoTime();
try {
Object result = method.invoke(target, args);
long cost = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
System.out.println("[LOG] ← " + methodName + " = " + result + " (cost: " + cost + "ms)");
return result;
} catch (InvocationTargetException e) {
long cost = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
System.err.println("[LOG] ✗ " + methodName + " threw " + e.getTargetException().getClass().getSimpleName()
+ " (cost: " + cost + "ms)");
throw e.getTargetException();
}
}
}
阿里百炼大模型平台多人共享账号用量统计代理服务。解决公司共用账号时无法区分个人用量的问题。适用场景:1)部署用量统计代理;2)统计多人Token用量和调用次数;3)管理大模型API调用配额。
创建代理实例并使用
调用 Proxy.newProxyInstance() 时需传入三要素:
-
ClassLoader:一般用目标对象的类加载器,如
target.getClass().getClassLoader() -
Class[] interfaces:目标对象实现的所有接口,如
new Class[]{UserService.class} - InvocationHandler:上面写的日志处理器实例
UserService realService = new UserServiceImpl();
UserService proxy = (UserService) Proxy.newProxyInstance(
realService.getClass().getClassLoader(),
realService.getClass().getInterfaces(),
new LoggingInvocationHandler(realService)
);
<p>// 后续所有调用都走代理,自动打印日志
proxy.getName(123);
proxy.updateName(123, "Alice");</p>进阶建议:提升实用性
生产中可进一步优化:
- 用 SLF4J 替代
System.out,支持日志级别、异步、结构化输出 - 加白名单/黑名单控制哪些方法需要日志(如跳过
toString()、hashCode()) - 提取公共日志模板,支持配置开关、采样率(如只记录耗时 >100ms 的调用)
- 结合 MDC 在日志中透传 traceId,便于链路追踪
不复杂但容易忽略:确保 InvocationHandler 中抛出的异常类型与原方法声明一致,否则编译可能通过但运行时报 UndeclaredThrowableException。实际开发中建议统一包装或声明 throws Throwable 并由上层处理。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










