使用CGLib实现动态代理

博客介绍了CGLib动态代理,程序执行时借助ASM jar包动态为被代理类生成代理子类,进而创建代理对象,因存在继承关系,父类不能用final修饰,还提及了CGLib动态代理的实现需导入两个架包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
	}
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值