// 被代理类
public class Host implements Rent{
public void rent() {
System.out.println("房东租房子...");
}
}
//代理的接口,用于规范行为
public interface Rent {
void rent();
}
//生成代理对象并执行方法
public class ProxyObject implements InvocationHandler {
Rent host = new Host();
//通过反射的方式执行目标方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("我是黄牛");
return method.invoke(host,args);
}
// 获得代理对象
Object getProxy(){
//被代理类
return Proxy.newProxyInstance(this.getClass().getClassLoader(),host.getClass().getInterfaces() ,this);
}
}
//测试
Rent proxy = (Rent) new ProxyObject().getProxy();
proxy.rent();
