java动态代理Dynamic Proxy
1.被代理对象的接口:
1 2 3 4 5 6 | package test.dynamicproxy; public interface TargetInterface { public void SayHello(); public int sum( int a , int b); } |
2.被代理的对象:
1 2 3 4 5 6 7 8 9 10 11 | package test.dynamicproxy; public class Target implements TargetInterface { public void SayHello(){ System.out.println( "Hello" ); } public int sum( int a, int b) { return a+b; } } |
3.InvocationHandler包装:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package test.dynamicproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class TargetInvocationHandler implements InvocationHandler { private Object object; public TargetInvocationHandler(Object obj){ this .object=obj; } public Object invoke(Object proxy, Method method, Object[] args2) throws Throwable { doBefore(); Object result = method.invoke(object, args2); doAfter(); return result; } public void doBefore(){ System.out.println( "do before" ); } public void doAfter(){ System.out.println( "do after" ); } } |
4.测试类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | package test.dynamicproxy; import java.lang.reflect.Proxy; public class TestDynamicProxy { /** * @param args */ public static void main(String[] args) { Target t= new Target(); TargetInvocationHandler handler= new TargetInvocationHandler(t); TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance( t.getClass().getClassLoader(), t.getClass().getInterfaces(), handler); proxy.SayHello(); int b=proxy.sum( 10 , 20 ); System.out.println(b); } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步