Aop底层原理(动态代理)
我们先来聊下静态代理
以租房为例,代理(Proxy)我们可以理解成中介,出租房子的人为房东(Host)
租房子的人为客户(Client)
- 定义一个接口Rent添加租房子的方法
public interface Rent {
public void rent();
}
- 房东要租房子就要实现Rent方法
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东出租房子");
}
}
- 中介(代理)作为平台也要实现Rent接口,同样房东委托中介中介就要接待
房东,Proxy类就要引入Host,同事时中介要带客户看房,收中介费,签合同
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
seeHouse();
host.rent();
fare();
hetong();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
//签租赁合同
public void hetong(){
System.out.println("签租赁合同");
}
}
- 客户找(Client)要租房子直接找中介,中介调用租房方法实现代理与客户联系
public class Client {
public static void main(String[] args) {
Proxy proxy = new Proxy(new Host());
proxy.rent();
}
}
PS:这是一个静态代理的例子代理类是固定的
动态代理(InvocationHandler实现)
- 动态生成代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object targetInterface;
public void setTargetInterface(Object targetInterface) {
this.targetInterface = targetInterface;
}
//生成得到代理类
public Object getProxyClass(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
targetInterface.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result=method.invoke(targetInterface,args);
return result;
}
private void log(String msg){
System.out.println("调用了"+msg+"方法");
}
}
- 客户(Client)实现动态代理
public class Client {
public static void main(String[] args) {
//真实角色
Host host=new Host();
//代理角色,现在还没有
ProxyInvocationHandler pih=new ProxyInvocationHandler();
//设置要代理的对象来实现接口
pih.setTargetInterface(host);
//动态生成代理类
Rent proxyClass = (Rent) pih.getProxyClass();
//实现代理方法
proxyClass.rent();
}
}