public class ProxyFactory {
private Object target;
public ProxyFactory(Object target) {
super();
this.target = target;
}
/**
* 得到代理对象
*/
public Object getProxyFactory() {
// 创建一个子类构造器
Enhancer enhancer = new Enhancer();
// 设置父类
enhancer.setSuperclass(obj.getClass());
// 设置回调,就是代理工厂
enhancer.setCallback(this);
// 在内存里生成代理对象
return enhancer.create();
}
/**
* 拦截方法
* @param obj 目标对象
* @param method 目标对象调用的方法
* @param args 方法参数
* @param methodProxy 方法代理
*/
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
// 前置增强
Object invoke = method.invoke(target, args);
// 后置增强
return invoke;
}
}
public static void main(String[] args) {
UserDaoImpl daoImpl = new UserDaoImpl();
ProxyFactory proxyFactory = new ProxyFactory(daoImpl);
UserDaoImpl daoImplFactory = (UserDaoImpl)proxyFactory.getProxyFactory();
daoImplFactory.play();
}