在 Java 中使用 Proxy(代理)(通常指 java.lang.reflect.Proxy 动态代理,也包括 CGLIB 等代理方式)时,开发者经常会遇到一些典型错误和坑。下面按常见程度和问题类型总结:
错误示例:
class UserService { }
Proxy.newProxyInstance(..., new Class[]{UserService.class}, ...); // 错误
原因:
解决:
Proxy.newProxyInstance(
loader,
interfaces,
null // 错误
);
原因:
InvocationHandler正确示例:
Proxy.newProxyInstance(
loader,
new Class[]{UserService.class},
(proxy, method, args) -> method.invoke(target, args)
);
(proxy, method, args) -> method.invoke(proxy, args);
结果:
StackOverflowError正确做法:
method.invoke(target, args);
UserServiceImpl proxy = (UserServiceImpl) Proxy.newProxyInstance(...);
错误原因:
✅ 正确:
UserService proxy = (UserService) Proxy.newProxyInstance(...);
(proxy, method, args) -> "hello"; // 实际方法返回 int
异常:
ClassCastException
try {
return method.invoke(target, args);
} catch (Exception e) {
return null;
}
问题:
UndeclaredThrowableException✅ 推荐:
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
@Service
public class UserService {
public void a() {
b(); // 代理无效
}
@Transactional
public void b() {}
}
原因:
this.b() 不经过代理对象解决:
AopContext.currentProxy()Proxy.newProxyInstance(...); // 每次调用都创建
问题:
✅ 缓存代理对象
proxy.equals(target); // false
代理对象和原对象不是同一个实例
Proxy.newProxyInstance(
target.getClass().getClassLoader(),
interfaces,
handler
);
错误:
异常:
IllegalArgumentException: interface not visible
| 类型 | 常见错误 |
|---|---|
| 使用方式 | 代理类而非接口 |
| 实现 | 忘记 InvocationHandler |
| 逻辑 | 自调用、递归 |
| 类型 | final / static / private |
| Spring | 代理失效 |
| 性能 | 重复创建 |
| 类加载 | ClassLoader 不匹配 |
如果你愿意,我可以:
直接贴代码或异常即可。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。