1,动态代理
分为2类
① 基于JDK(1.5以后的版本)
接口类:
点击查看代码
public interface IDAO {
public int save();
public int remove();
public int modify();
public int findAll();
}
点击查看代码
public class DeptDAO implements IDAO{
@Override
public int save() {
return 1;
}
@Override
public int remove() {
return 2;
}
@Override
public int modify() {
return 3;
}
@Override
public int findAll() {
return 4;
}
}
点击查看代码
package com.bh.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyProxy implements InvocationHandler {
//要被代理的类
private Object delegateEnhanced;
/*绑定要被代理的类*/
public Object bind(Object delegate){
this.delegateEnhanced = delegate;
Object createdObject = Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
//要增强被代理类的所有方法的功能
delegate.getClass().getInterfaces(), this);
return createdObject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("开始spa==============");
Object result = method.invoke(this.delegateEnhanced, args);
System.out.println("结束spa==============");
return result;
}
}
点击查看代码
public class Test {
public static void main(String[] args) {
//查看$Proxy0.class的方法
// System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
//原厂产品
DeptDAO deptDAO = new DeptDAO();
//代理商
MyProxy myProxy = new MyProxy();
//代理商 在原厂产品上增强
IDAO deptDaoEnhance = (IDAO)myProxy.bind(deptDAO);
int i = deptDaoEnhance.findAll();//执行时生成了一个$Proxy0.class里面调用代理类的invoke方法
System.out.println(i);
}
}
点击查看结果
开始spa==============
结束spa==============
4