接口
package com.liyan.reflection04;
//租房
public interface Rent {
public void rent();
}
真实对象
package com.liyan.reflection04;
//房东
public class Host implements Rent{
public void rent() {
System.out.println("房东要出租房子啦");
}
}
代理类
package com.liyan.reflection04;
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);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(target,args);
return result;
}
}
我
package com.liyan.reflection04;
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(host);
//生成动态代理
Rent r = (Rent)pih.getProxy();
r.rent();
}
}