在 MethodInterceptor 中获取目标
如何在拦截器中获取目标对象?
bindInterceptor(subclassesOf(A.class), any(), new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
A a = getTarget(); //how?
return methodInvocation.proceed();
}
});
UPD 实际上,有基于反射的解决方案,但希望还有其他解决方案。
private static Object getTarget(MethodInvocation methodInvocation) throws NoSuchFieldException, IllegalAccessException {
return getFieldValue(methodInvocation, "proxy");
}
private static Object getFieldValue(Object obj, String field) throws NoSuchFieldException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(field);
f.setAccessible(true);
return f.get(obj);
}
How I can get Target object in my interceptor?
bindInterceptor(subclassesOf(A.class), any(), new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
A a = getTarget(); //how?
return methodInvocation.proceed();
}
});
UPD
Actually, there is reflection based solution, but it hope that there other solutions..
private static Object getTarget(MethodInvocation methodInvocation) throws NoSuchFieldException, IllegalAccessException {
return getFieldValue(methodInvocation, "proxy");
}
private static Object getFieldValue(Object obj, String field) throws NoSuchFieldException, IllegalAccessException {
Field f = obj.getClass().getDeclaredField(field);
f.setAccessible(true);
return f.get(obj);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不就是
methodInitation.getThis()
吗?Isn't it just
methodInvocation.getThis()
?