/**
*定义一个借口
**/
public interface RentHouse {
void rent();//房屋出租
void charge(String str);//出租费用收取
}
public class HouseOwner implements RentHouse {
public void rent() {
System.out.println("I want to rent my house");
}
public void charge(String str) {
System.out.println("You get : " + str + " RMB HouseCharge.");
}
}
public class DynamicProxy implements InvocationHandler {
// 这个就是我们要代理的真实对象,即房东
private Object subject;
// 构造方法,给我们要代理的真实对象赋初值
public DynamicProxy(Object subject) {
this.subject = subject;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在代理真实对象前我们可以添加一些自己的操作,中介收取中介费
System.out.println("before "+method.getName()+" house");
System.out.println("Method:" + method.getName());
// 如果方法是 charge 则中介收取100元中介费
if (method.getName().equals("charge")) {
method.invoke(subject, args);
System.out.println("I will get 100 RMB ProxyCharge.");
} else {
// 当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用
method.invoke(subject, args);
}
// 在代理真实对象后我们也可以添加一些自己的操作
System.out.println("after "+method.getName()+" house");
return null;
}
}
public class Client {
public static void main(String[] args)
{
// 我们要代理的真实对象--房东
HouseOwner houseOwner = new HouseOwner();
// 我们要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法的
InvocationHandler handler = new DynamicProxy(houseOwner);
/*
* 通过Proxy的newProxyInstance方法来创建我们的代理对象,我们来看看其三个参数
* 第一个参数 handler.getClass().getClassLoader() ,我们这里使用handler这个类的ClassLoader对象来加载我们的代理对象
* 第二个参数realSubject.getClass().getInterfaces(),我们这里为代理对象提供的接口是真实对象所实行的接口,表示我要代理的是该真实对象,这样我就能调用这组接口中的方法了
* 第三个参数handler, 我们这里将这个代理对象关联到了上方的 InvocationHandler 这个对象上
*/
RentHouse rentHouse = (RentHouse) Proxy.newProxyInstance(handler.getClass().getClassLoader(), houseOwner
.getClass().getInterfaces(), handler);//一个动态代理类,中介
System.out.println(rentHouse.getClass().getName());
rentHouse.rent();
rentHouse.charge("10000");
}
}
com.sun.proxy.$Proxy0 before rent house Method:rent I want to rent my house after rent house before charge house Method:charge You get : 10000 RMB HouseCharge. I will get 100 RMB ProxyCharge. after charge house Process finished with exit code 0
Object invoke(Object proxy, Method method, Object[] args) throws Throwable
Object invoke(Object proxy, Method method, Object[] args) throws Throwable //proxy: 指代我们所代理的那个真实对象 //method: 指代的是我们所要调用真实对象的某个方法的Method对象 //args: 指代的是调用真实对象某个方法时接受的参数
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException //loader:一个ClassLoader对象,定义了由哪个ClassLoader对象来对生成的代理对象进行加载 //interfaces:一个Interface对象的数组,表示的是我将要给我需要代理的对象提供一组什么接口,如果我提供了一组接口给它,那么这个代理对象就宣称实现了该接口(多态),这样我就能调用这组接口中的方法了 //h:一个InvocationHandler对象,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有