Spring 高级 jdk代理原理-基础篇
一、简单代理
package com.mangoubiubiu.show.a13; public class A13 { interface Foo{ void foo(); } static class Target implements Foo{ @Override public void foo() { System.out.println("target foo"); } } public static void main(String [] param){ Foo proxy = new $Proxy0(); } }
package com.mangoubiubiu.show.a13; import com.mangoubiubiu.show.a13.A13.Foo; import com.mangoubiubiu.show.a13.A13.Target; public class $Proxy0 implements Foo { @Override public void foo() { System.out.println("功能增强"); new Target().foo(); } }
打印测试
二、初步进阶
package com.mangoubiubiu.show.a13; public class A13 { interface Foo{ void foo(); } interface InvocationHandler{ void invoke(); } static class Target implements Foo{ @Override public void foo() { System.out.println("target foo"); } } public static void main(String [] param){ Foo proxy = new $Proxy0(() -> { System.out.println("调用目标方法"); new Target().foo(); }); proxy.foo(); } }
package com.mangoubiubiu.show.a13; import com.mangoubiubiu.show.a13.A13.Foo; import com.mangoubiubiu.show.a13.A13.Target; import com.mangoubiubiu.show.a13.A13.InvocationHandler; public class $Proxy0 implements Foo { private InvocationHandler h; public $Proxy0(InvocationHandler h){ this.h=h; } @Override public void foo() { h.invoke(); } }
打印测试
三、再次进阶
package com.mangoubiubiu.show.a13; import java.lang.reflect.Method; public class A13 { interface Foo{ void foo() throws Throwable; void bar() throws Throwable; } interface InvocationHandler{ void invoke(Method method,Object[] args ) throws Throwable; } static class Target implements Foo{ @Override public void foo() { System.out.println("target foo"); } @Override public void bar() { System.out.println("target bar"); } } public static void main(String [] param) throws Throwable { Foo proxy = new $Proxy0((Method method,Object[] args ) -> { System.out.println("before"); method.invoke(new Target(),args); }); proxy.foo(); proxy.bar(); } }
package com.mangoubiubiu.show.a13; import com.mangoubiubiu.show.a13.A13.Foo; import com.mangoubiubiu.show.a13.A13.Target; import com.mangoubiubiu.show.a13.A13.InvocationHandler; import java.lang.reflect.Method; public class $Proxy0 implements Foo { private InvocationHandler h; public $Proxy0(InvocationHandler h){ this.h=h; } @Override public void foo() throws Throwable { Method foo = Foo.class.getMethod("foo"); h.invoke(foo,new Object[0]); } @Override public void bar() throws Throwable { Method bar = Foo.class.getMethod("bar"); h.invoke(bar,new Object[0]); } }