这篇文章将为大家详细讲解有关深入浅析java 1.8 中动态代理的原理,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

JDK8动态代理源码分析
动态代理的基本使用就不详细介绍了:
例子:
class proxyed implements pro{
@Override
public void text() {
System.err.println("本方法");
}
}
interface pro {
void text();
}
public class JavaProxy implements InvocationHandler {
private Object source;
public JavaProxy(Object source) {
super();
this.source = source;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object invoke = method.invoke(source, args);
System.out.println("after");
return invoke;
}
public Object getProxy(){
return Proxy.newProxyInstance(getClass().getClassLoader(), source.getClass().getInterfaces(), this);
}
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
//第一种,自己写
//1.设置saveGeneratedFiles值为true则生成 class字节码文件方便分析
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
//2.获取动态代理类
Class proxyClazz = Proxy.getProxyClass(pro.class.getClassLoader(),pro.class);
//3.获得代理类的构造函数,并传入参数类型InvocationHandler.class
Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
//4.通过构造函数来创建动态代理对象,将自定义的InvocationHandler实例传入
pro iHello = (pro) constructor.newInstance(new JavaProxy(new proxyed()));
//5.通过代理对象调用目标方法
iHello.text();
//第二种,调用JDK提供的方法,实现了2~4步
Proxy.newProxyInstance(JavaProxy.class.getClassLoader(),proxyed.class.getInterfaces(),new JavaProxy(new proxyed()));
}
}