JDK代理以前性能不怎么样,但1.6版本却有很大提升
/**
* 行为接口
*
* @author Administrator
*
*/
public interface Study {
public void doStudy();
}
/**
* 目标对象
*
* @author Administrator
*
*/
public class StudyImpl implements Study {
@Override
public void doStudy() {
System.out.println("study jdk proxy");
}
}
/**
* 代理类
* @author Administrator
*
*/
public class JDKProxy implements InvocationHandler {
private Study s;
public JDKProxy(Study s) {
this.s = s;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("before jdkproxy");
method.invoke(s, args);
System.out.println("after jdkproxy");
return null;
}
}
应用中进行调用:
public class Test {
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException,
InvocationTargetException {
Class clazz = StudyImpl.class;//获取目标类的Class对象
Study st = new StudyImpl();//实例化一个目标类
Class proxClass = Proxy.getProxyClass(clazz.getClassLoader(), clazz
.getInterfaces());//通过Proxy静态方法,获取一个于目标类实现同样接口的Class对象,也可以说是兄弟类
Constructor c = proxClass
.getConstructor(new Class[] { InvocationHandler.class });//给这个类一个指定的公开的构造方法
Study ds = (Study) c.newInstance(new Object[] { new JDKProxy(st) });//实例化一个代理类
}
}