Client
package com.kuang.demo;
public class Client {
public static void main(String[] args) {
Host host = new Host();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(host);
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
Host
package com.kuang.demo;
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子");
}
}
ProxyInvocationHandler
package com.kuang.demo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target, args);
return result;
}
}
Rent
package com.kuang.demo;
public interface Rent {
public void rent();
}