jdk的动态代理
要求:
1:实现InvocationHandler
2:使用Proxy.newProxyInstance产生代理对象
3:被代理的对象必须要实现接口
public class JDKProxy implements InvocationHandler {
private Object target ;
public Object createProxyObject(Object obj) {
this.target = obj ;
Object proxyObj = Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
this) ;
return proxyObj ;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object obj = null ;
if ("addUser".equals(method.getName())) {
System.out.println("日志记录");
}
System.out.println(method.getName()+"-------------------" + args.length);
obj = method.invoke(target, args) ;
return obj;
}
}
测试类:
public static void main(String[] args) {
UserDao uDao = new UserDaoImpl() ;
UserDao jdkProxy = (UserDao)new JDKProxy().createProxyObject(uDao) ;
jdkProxy.addUser(new User()) ;
}
这里代理类是dao的实现类 , 返回一个实现类的代理 , 代理类去执行方法的时候 自动去调用invoke方法,一般用来做日志
对任何对象进行代理拦截,可以是没有实现接口的对象
cglib的代理
public class CGLibProxy implements MethodInterceptor {
private Object target ;
public Object createProxyObject(Object obj){
this.target = obj ;
Enhancer enhancer = new Enhancer() ;
enhancer.setSuperclass(obj.getClass()) ;
enhancer.setCallback(this) ;
Object proxyObj = enhancer.create() ;
return proxyObj ;
}
public Object intercept(Object proxy, Method method, Object[] args,
MethodProxy methodProxy) throws Throwable {
Object obj = null ;
if ("addUser".equals(method.getName())) {
System.out.println("日志记录");
}
obj = method.invoke(target, args) ;
return obj;
}
}
测试类:
public static void main(String[] args) {
UserDao uDao = new UserDaoImpl() ;
UserDao cgProxy = (UserDao)new CGLibProxy().createProxyObject(uDao) ;
cgProxy.updateUser(new User()) ;
}
优点:代理的对象可以使没有实现任何接口的类