Java动态代理
2019-04-13 本文已影响0人
Lesss
- 下面以买房子为例子
public interface Sale {
void sell();
}
- 房东出售房子
public class Landlord implements Sale{
@Override
public void sell() {
System.out.println("我是房东我要出售房子");
}
}
- 代理类
public class Intermediary implements InvocationHandler {
private Object delegate;
public Intermediary(Object delegate) {
this.delegate = delegate;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("准备执行invoke...");
Object result=method.invoke(delegate, args);
System.out.println("执行完成...");
return result;
}
}
- 执行
Landlord landlord = new Landlord();
InvocationHandler handler = new Intermediary(landlord);
Sale proxy=(Sale) Proxy.newProxyInstance(landlord.getClass().getClassLoader(), landlord.getClass().getInterfaces(), handler);
proxy.sell();
- 关于动态代理的优点
相比于静态代理,动态代理简化了代码量