为什么:当我想调同样的方法但又不一样的结果,可以使用动态代理,使被调用者没有感觉有改动
所谓动态代理是通过代码给目标类生成代理类
public class ProxyFac {
//创建一个被代理的目标对象,因为此时不确定要代理的目标对象是什么类型,所以用object
private Object obj;
public ProxyFac(Object obj) {
this.obj = obj;
}
//创建一个对象用来返回代理
public Object getProxy(){
//获得代理实例需要传入类加载器(代理对象的),(与被代理对象实现相同)接口数组,执行处理器
ClassLoader classLoader = ProxyFac.class.getClassLoader();
Class<?>[] interfaces = obj.getClass().getInterfaces();
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//proxy:代理对象
//method:执行的方法
//参数列表
//跟静态代理模式一样,方法还交还给被代理人做。需要修改的代码通过if判断来修改,或者在方法执行前后也可以加一些操作
System.out.println("方法执行前。。。。参数:"+ Arrays.toString(args));
Object result = method.invoke(obj, args);
System.out.println("方法执行后。。。。结果:"+ result);
return result;
}
};
return Proxy.newProxyInstance(classLoader,interfaces,invocationHandler);
}
}
接口和实现类
public interface Move {
void move();
}
//代理对象
public class Car implements Move{
@Override
public void move() {
System.out.println("我可以移动");
}
}
测试类
public class Test {
public static void main(String[] args) {
ProxyFac proxyFac = new ProxyFac(new Car());
//不确定能转成什么类但能确定接口
Move proxy = (Move)proxyFac.getProxy();
proxy.move();
}
}