动态代理其实就是java.lang.reflect.Proxy类动态的根据您指定的所有接口生成一个class,该class会继承Proxy类,并实现所有你指定的接口(您在参数中传入的接口数组);然后再利用您指定的classloader将class加载进系统,最后生成这样一个类的对象,并初始化该对象的一些值,如invocationHandler,以即所有的接口对应的Method成员。 初始化之后将对象返回给调用的客户端。这样客户端拿到的就是一个实现你所有的接口的Proxy对象
- 业务接口类
public interface BusinessInterface {
public void processBusiness();
}
- 业务实现类
public class BusinessImpl implements BusinessInterface {
@override
public void processBusiness() {
System.out.println("执行业务");
}
}
- 业务代理类
public BusinessProcessorHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throwsThrowable {
System.out.println("You can do something here before process your business");
Object result = method.invoke(target, args);
System.out.println("You can do something here after process your business");
return result;
}
}
- 具体应用类(关键代码)
public static void main(String[] args) {
BusinessInterface bi = new BusinessImpl();
BusinessProcessorHandler handler = new BusinessProcessorHandler(bi);
BusinessInterface bp = (BusinessInterface) Proxy.newProxyInstance(bpimpl.getClass().getClassLoader(),
bpimpl.getClass().getInterfaces(), handler);
bp.processBusiness();
}