17.0、动态代理
ProxyInvoctionHandler.java文件
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理的实例,三个参数:第一个加载类的位置,第二个代理的接口,第三个InvocationHandler
public Object getTarget() {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
}
//处理代理的实例,并且返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodname = method.getName();
fare();
Object result = method.invoke(target,args);
return result;
}
public void fare() {
System.out.println("在房子出租前中介需要收取百分之五十的中介费用!");
}
}
Client.java文件
public class Client {
public static void main(String[] args) {
RentImpl rentimpl = new RentImpl();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(rentimpl);
Rent rent = (Rent) pih.getTarget();
rent.rent();
}
}
Rent.java接口文件
public interface Rent {
public void rent();
}
RentImpl.java接口实现类文件
public class RentImpl implements Rent {
@Override
public void rent() {
System.out.println("房子出租!");
}
}

3万+

被折叠的 条评论
为什么被折叠?



