CGLib动态代理
程序执行时通过ASM(开源的Java字节码编辑库,操作字节码)jar包动态地为被代理类生成一个代理子类,通过该代理子类创建代理对象,由于存在继承关系,所以父类不能使用final修饰。
CGLib动态代理实现
1、导入两个架包
package com.zzu.cglib;
public class CalculatorService {
public int add(int a, int b) {
int result = a+b;
return result;
}
public int sub(int a, int b) {
int result = a-b;
return result;
}
public int mul(int a, int b) {
int result = a*b;
return result;
}
public int div(int a, int b) {
int result = a/b;
return result;
}
}
public class ProxyFactory {
static CalculatorService target;
static Callback callback = new MethodInterceptor() {
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
String name = method.getName();
System.out.println(this.getClass().getName()+":The "+name+" method begins.");
System.out.println(this.getClass().getName()+":Parameters of the "+name+" method: ["+args[0]+","+args[1]+"]");
Object result = method.invoke(target, args);
System.out.println(this.getClass().getName()+":Result of the "+name+" method:"+result);
System.out.println(this.getClass().getName()+":The add method ends.");
return result;
}
};
public static Object getProxy(CalculatorService target) {
ProxyFactory.target = target;
Enhancer enhancer = new Enhancer();//创建CGLib的核心类对象
enhancer.setSuperclass(target.getClass());//设置父类
enhancer.setCallback(callback);//设置回调
return enhancer.create();//创建代理对象
}
}
public class Test {
public static void main(String[] args) {
CalculatorService calculatorService = (CalculatorService) ProxyFactory.getProxy(new CalculatorService());
int result = calculatorService.add(1, 1);
System.out.println(result);
}
}
运行结果