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();
上一篇 下一篇

猜你喜欢

热点阅读