java - reflection.proxy not valid when override -


it seems reflection.proxy not expected when there overriden methods. in detail, starting simple application:

static void debug( string fmt, object... args ) {     system.out.println( string.format(fmt,args)); }  interface {     void m1();     void m2(); }  static class implements {     public void m1() { system.out.println( "a.m1" ); m2(); }     public void m2() { system.out.println( "a.m2" ); } }  static class b extends {     @override     public void m2() { system.out.println( "b.m2" ); } }   public static void main( string[] args ) {     b b = new b();     b.m1(); } 

the output is, expected:

a.m1 b.m2 

now, try proxify calls methods of "b b". following new code added:

static public class helloinvocationhandler implements invocationhandler {      proxied;      helloinvocationhandler( 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);     pb = (i) proxy.newproxyinstance(             i.class.getclassloader(),             new class[] { i.class },             handler);      pb.m1(); } 

and new output is:

helloinvocationhandler: invoke method m1 a.m1 b.m2 

as can see, call "m2" not executed accross proxy. if call b's methods accross proxy, line "helloinvocationhandler: invoke method m2" should appear in ouput.

any hint?

thanks.

you can use cglib library create proxy. use enhancer.create(b.class, new helloinvocationhandler()) to intercept method invocations. it's not harder using jdk proxy, more flexible. should in case. interceptor should implemented 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);     } } 

use this:

b pb = (b)enhancer.create(b.class, new helloinvocationhandler()); pb.m1(); 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -