动态代理
需要了解两个类Proxy和InvocationHandler
- Proxy:代理
- InvocationHandler:调用处理程序
Rent:
package com.kakafa.demo01;
//需要被代理的接口
public interface Rent {
public void rent();
}
Host:
package com.kakafa.demo01;
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子啦!");
}
}
ProxyInvocationHandler:
package com.kakafa.demo01;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Rent rent;
public void setRent(Rent rent){
this.rent=rent;
}
//生成代理对象的方法
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this );
}
//处理代理实例,并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
//动态代理的本质,就是用反射机制实现
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seeHouse(){
System.out.println("看房子");
}
public void fare(){
System.out.println("收费");
}
}
Client:
package com.kakafa.demo01;
public class Client {
public static void main(String[] args) {
//真实角色
Host host=new Host();
//代理角色:现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host);
Rent proxy = (Rent)pih.getProxy();
proxy.rent();
}
}