要生成字节码文件,要在main里额外加一句代码
这是生成JDK代理类的字节码文件
//设置
//key来源于ProxyGenerator这个类
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles","true");//生成的字节码文件保存在working directory
public class Test {
public static void main(String[] args) {
//setProperty的key在ProxyGenerator类里的saveGeneratedFiles变量里面,
// 只有下载了完整的ProxyGenerator代码,才能看见参数
System.setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
//参数1:委托类的classloader
//参数2:委托类实现的所有父接口,getInterfaces能获得类对象的全部父接口
//参数3:invocationHandler,它的invoke()里就是代理对象执行的方法内容
// (委托类方法的执行 + 增强)
BuyBreakFast proxy=(BuyBreakFast) Proxy.newProxyInstance(Son.class.getClassLoader(), Son.class.getInterfaces(), new InvocationHandler() {
/*proxy:是用newProxyInstance生成的代理对象
*method:是委托类里的方法
*args:是委托类里的方法参数
*Object:是委托类里面函数的返回值*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("method:"+method.getName());
Object invoke = method.invoke(new Son(), args);//执行委托类本身要执行的方法
System.out.println("一碗蛋酒、一份烤肠"); //做额外的增强
return invoke;
}
});
proxy.buyBreakFast();//执行代理对象方法,就会调用invocationHandler的invoke()
}
}
重新运行后,会看见生成$Proxy0.class文件
这是生成Cglib代理类的字节码文件
//保存cglib动态代理生成的字节码文件
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,
"D:\\WorkSpace\\j29_workspace\\codes\\day01-design-pattern\\demo5-cglib-dynamic-proxy");//将字节码文件存储在指定绝对路径
PS:key是DebuggingClassWriter的DEBUG_LOCATION_PROPERTY属性,value是字节码文件存储路径