版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ren365880/article/details/80916434
代理就是一个对象的代理对象,代理对象存在的价值主要(不是唯一)就是对访问真实业务对象进行拦截。
static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
newProxyInstance方法用来返回一个代理对象,这个方法总共有3个参数,ClassLoader loader用来指明生成代理对象使用哪个类装载器,Clas < ?>[] interfaces用来指明生成哪个对象的代理对象,通过接口指定,InvocationHandler h用来指明产生的这个代理对象要做什么事情。所以我们只需要调用newProxyInstance方法就可以得到某一个对象的代理对象了。
举一个可以使用代理对象的场景,小A购买了一辆汽车,汽车上路前必须上牌才能够上路,使用代理对象对汽车上路前进行是否上牌的检查(在代码中就是对访问上路方法的拦截)。下面代码跑下更清晰。
交通工具接口:
public interface Vehicle {
String run(String name);
}
汽车实现了交通工具接口:
public class Car implements Vehicle{
@Override
public String run(String name) {
System.out.println(name+"在公路上行驶!");
return null;
}
}
代理对象:
public class RPCProxy {
private Object object;
public Object getProxy(Object obj){
this.object = obj;
return java.lang.reflect.Proxy.newProxyInstance(RPCProxy.class.getClassLoader(),
obj.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//以下是对访问方法的拦截业务逻辑
if("run".equals(method.getName()) && "汽车".equals(args[0])) {
System.out.println("汽车没上牌,想要上路必须上牌!");
System.out.println("花了500上牌");
}else if("run".equals(method.getName()) && "自行车".equals(args[0])) {
System.out.println("自行车不用上牌!");
}
return method.invoke(object, args);
}
});
}
}
main函数跑一下:
public class Test {
public static void main(String[] args) {
Vehicle l = (Vehicle) new RPCProxy().getProxy(new Car());
l.run("汽车");
System.out.println("======================");
l.run("自行车");
}
}
结果:
汽车没上牌,想要上路必须上牌!
花了500上牌
汽车在公路上行驶!
======================
自行车不用上牌!
自行车在公路上行驶!