接口
//接口
public interface Rent {
public void rent();
}
被代理类
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要租房!!!");
}
}
动态代理类
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;
}
//生成代理,只需要修改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);
giveMoney();
return result;
}
public void seeHouse(){
System.out.println("中介带人去看房子!!!");
}
public void giveMoney(){
System.out.println("看中给钱!!!");
}
}
测试类
public class Client {
public static void main(String[] args) {
//真实角色
Host host=new Host();
//代理角色
ProxyInvocationHandler proxyInvocationHandler = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象!
proxyInvocationHandler.setRent(host);
Rent proxy = (Rent) proxyInvocationHandler.getProxy();
proxy.rent();
}
}
听了狂神的动态代理有点懵逼,所以记录下,说不定往后学就突然开窍了