覆盖时reflection.proxy无效 [英] reflection.proxy not valid when override
问题描述
当有覆盖方法时,reflection.proxy 似乎不是预期的.详细来说,从简单的应用开始:
It seems reflection.proxy does not what is expected when there are overriden methods. In detail, starting with simple application:
static void debug( String fmt, Object... args ) {
System.out.println( String.format(fmt,args));
}
interface I {
void m1();
void m2();
}
static class A implements I {
public void m1() { System.out.println( "A.m1" ); m2(); }
public void m2() { System.out.println( "A.m2" ); }
}
static class B extends A {
@Override
public void m2() { System.out.println( "B.m2" ); }
}
public static void main( String[] args )
{
B b = new B();
b.m1();
}
输出如预期:
A.m1
B.m2
现在,我们尝试代理对B b"的所有方法的调用.添加以下新代码:
Now, we try to proxify the calls to all methods of "B b". Following new code is added:
static public class HelloInvocationHandler implements InvocationHandler {
I proxied;
HelloInvocationHandler( I proxied ) {
this.proxied = proxied;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String methodName = method.getName();
debug( "HelloInvocationHandler: invoke method %s", methodName);
return method.invoke(proxied,args);
}
}
public static void main( String[] args )
{
B b = new B();
HelloInvocationHandler handler = new HelloInvocationHandler(b);
I pb = (I) Proxy.newProxyInstance(
I.class.getClassLoader(),
new Class[] { I.class },
handler);
pb.m1();
}
新的输出是:
HelloInvocationHandler: invoke method m1
A.m1
B.m2
如您所见,对m2"的调用不会跨代理执行.如果对 B 的方法的所有调用都跨代理,则输出中应出现一行HelloInvocationHandler:invoke method m2".
as you can see, the call to "m2" is not executed accross the proxy. If all call to B's methods was accross the proxy, a line "HelloInvocationHandler: invoke method m2" should appear in the ouput.
有什么提示吗?
谢谢.
推荐答案
您可以使用 CGLib 库来创建代理.使用 Enhancer.create(B.class, new HelloInvocationHandler())
来拦截方法调用.它并不比使用 JDK Proxy
难,但要灵活得多.应该对你的情况有所帮助.拦截器应该这样实现:
You can use CGLib library to create proxy. Use Enhancer.create(B.class, new HelloInvocationHandler())
to to intercept method invocations. It's not harder than using JDK Proxy
, but much more flexible. Should help in your case. The interceptor should be implemented like this:
public class HelloInvocationHandler implements MethodInterceptor {
public Object intercept(Object object, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
debug( "HelloInvocationHandler: invoke method %s", method.getName());
return methodProxy.invokeSuper(object, args);
}
}
像这样使用它:
B pb = (B)Enhancer.create(B.class, new HelloInvocationHandler());
pb.m1();
这篇关于覆盖时reflection.proxy无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!