摘要: JDK Dynamic Proxy_JDK动态代理
JDK Dynamic Proxy_JDK动态代理
更详细的在http://my.oschina.net/xinxingegeya/blog/297410
Dynamic Proxy :
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.
一个简单的示例:
下面贴出代码来,也没什么好说的
Basicfunc.java
package com.lyx.other;
public interface Basicfunc {
public void method1();
}
Example1.java
package com.lyx.other;
public class Example1 implements Basicfunc {
public void method1() {
System.out.println("executing method 1");
}
}
MyInvocationHandler.java
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.java
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======
© 著作权归作者所有