java动态代理Dynamic Proxy
1.被代理对象的接口:
package test.dynamicproxy; public interface TargetInterface { public void SayHello(); public int sum(int a ,int b); }
2.被代理的对象:
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包装:
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.测试类:
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); } }