JDK Dynamic Proxy_JDK動態代理java
更詳細的在http://my.oschina.net/xinxingegeya/blog/297410ui
Dynamic Proxy :this
In this , proxies are created dynamically through reflection(反射). This functionality is added from JDK 1.3 . Dynamic proxy form the basic building block of Spring AOP.spa
一個簡單的示例:.net
下面貼出代碼來,也沒什麼好說的代理
Basicfunc.javacode
package com.lyx.other; public interface Basicfunc { public void method1(); }
Example1.javaorm
package com.lyx.other; public class Example1 implements Basicfunc { public void method1() { System.out.println("executing method 1"); } }
MyInvocationHandler.javablog
package com.lyx.other; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } public Object getTarget() { return this.target; } public void setTarget(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] params) throws Throwable { long a = System.currentTimeMillis(); Object result = method.invoke(this.target, params); System.out.println("total time taken " + (System.currentTimeMillis() - a)); return result; } }
MainClass.javaget
package com.lyx.other; import java.lang.reflect.Proxy; public class MainClass { public static void main(String[] args) { Example1 ex = new Example1(); Basicfunc proxied = (Basicfunc) Proxy.newProxyInstance( MainClass.class.getClassLoader(), ex.getClass().getInterfaces(), new MyInvocationHandler(ex)); proxied.method1(); } }
======END======