设计模式之cglib动态代理

阅读更多
cglib是针对类来实现代理的,原理是生成一个被代理类的子类。
1、创建被代理类
package cglib;

public class Driver {
	
	public String doAction() {
		System.out.println("驾驶员喝酒了,需要找代驾");
		return "去XXX地方";
	}
}



2、创建代理类
package cglib;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class Daijia implements MethodInterceptor {
	
	public Object getInstance(String className) throws ClassNotFoundException {
		Enhancer enhancer = new Enhancer();//加强器,用来创建动态代理类
		Class clazz = Class.forName(className);
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
		return enhancer.create();
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		System.out.println("我是代驾,您需要去哪里?");
		System.out.println("---------------");
		proxy.invokeSuper(obj, args);
		System.out.println("---------------");
		System.out.println("到达目的地");
		return null;
	}

}



3、测试类
package cglib;

public class CglibTest {

	public static void main(String[] args) throws ClassNotFoundException {
		Driver driver = (Driver)new Daijia().getInstance("cglib.Driver");
		driver.doAction();
	}

}

你可能感兴趣的:(设计模式之cglib动态代理)