1. 程式人生 > >動態代理的實現

動態代理的實現

第一種方式:JDBC

在這裡插入圖片描述

public class WorkerProxy implements InvocationHandler{

	private Object target;
	
	public WorkerProxy(Object target) {
		// TODO Auto-generated constructor stub
		this.target = target;
	}
	
	@Override
	public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("員工蓋房子");
		return arg1.invoke(target, arg2);
	}
	
	
}

測試類

			IBuilder builder1 = (IBuilder) Proxy.newProxyInstance(IBuilder.class.getClassLoader(), 
					new Class[]{IBuilder.class}, 
					new WorkerProxy(new Boss()));
			builder1.buildHouse();

第二種方法,cglib

代理類通過位元組碼技術建立一個被代理類的子類例項

public class WorkerProxy implements MethodInterceptor{
	private Enhancer enhancer = new Enhancer();
	
	public Object getProxy(Class<?> clazz) {
		//設定需要建立子類的類
		enhancer.setSuperclass(clazz);
		enhancer.setCallback(this);
		//通過位元組碼技術,動態建立子類例項
		return enhancer.create();
	}

	@Override
	public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
		System.out.println("員工建房子");
		//通過代理,呼叫父類的方法
		return arg3.invokeSuper(arg0, arg2);
	}

}

測試類

		WorkerProxy worker = new WorkerProxy();
		IBuilder builder = (IBuilder) worker.getProxy(Boss.class);
		builder.buildHouse();

第三種:javassist

javassist.util.proxy 或使用org.apache.ibatis.javassist.util.proxy

public class WorkerProxy1 implements MethodHandler{

	@Override
	public Object invoke(Object arg0, Method arg1, Method arg2, Object[] arg3) throws Throwable {
		// TODO Auto-generated method stub
		System.out.println("PROXY");
		return arg2.invoke(arg0, arg3);
	}

}

測試程式碼

			ProxyFactory factory = new ProxyFactory();
			factory.setSuperclass(Boss.class);
			Class<?> clazz = factory.createClass();
			IBuilder testDemo = (IBuilder) clazz.newInstance();
			((ProxyObject)testDemo).setHandler(new WorkerProxy1());
			testDemo.buildHouse();