Java 动态代理问题:HandlerXXX,HandlerYYY分别实现了InvocationHandler,请问如何同时加入,
答案:1 悬赏:80
解决时间 2021-02-08 10:29
- 提问者网友:不懂我就别说我变
- 2021-02-07 15:42
Java 动态代理问题:HandlerXXX,HandlerYYY分别实现了InvocationHandler,请问如何同时加入,
最佳答案
- 二级知识专家网友:邪性洒脱
- 2021-02-07 16:26
首先简要说明一下动态代理的原理:
我们调用Proxy.newProxyInstance所生成的代理对象的方法,其内部会调用InvocationHandler 中的invoke方法,而该方法会通过反射调用真实对象的指定方法。
对于你写的//InvocationHandler ihy=new AnimalHandlerYYY(ihx);来说,ihx本身并未实现Animal接口,所以调用它的shout方法会出错。
你可以尝试写成下面这样子,我猜能实现你想要的结果:
Animal animal = new Dog();
InvocationHandler ihx = new AnimalHandlerXXX(animal);
Animal proxy = (Animal) Proxy.newProxyInstance(animal.getClass()
.getClassLoader(), animal.getClass().getInterfaces(), ihx);
InvocationHandler ihy = new AnimalHandlerYYY(proxy);
proxy = (Animal) Proxy.newProxyInstance(animal.getClass()
.getClassLoader(), animal.getClass().getInterfaces(), ihy);
InvocationHandler ihz = new AnimalHandlerZZZ(proxy);
proxy = (Animal) Proxy.newProxyInstance(animal.getClass()
.getClassLoader(), animal.getClass().getInterfaces(), ihz);
proxy.shout();
估计说的不太明白,看看例子也许会明白些
我们调用Proxy.newProxyInstance所生成的代理对象的方法,其内部会调用InvocationHandler 中的invoke方法,而该方法会通过反射调用真实对象的指定方法。
对于你写的//InvocationHandler ihy=new AnimalHandlerYYY(ihx);来说,ihx本身并未实现Animal接口,所以调用它的shout方法会出错。
你可以尝试写成下面这样子,我猜能实现你想要的结果:
Animal animal = new Dog();
InvocationHandler ihx = new AnimalHandlerXXX(animal);
Animal proxy = (Animal) Proxy.newProxyInstance(animal.getClass()
.getClassLoader(), animal.getClass().getInterfaces(), ihx);
InvocationHandler ihy = new AnimalHandlerYYY(proxy);
proxy = (Animal) Proxy.newProxyInstance(animal.getClass()
.getClassLoader(), animal.getClass().getInterfaces(), ihy);
InvocationHandler ihz = new AnimalHandlerZZZ(proxy);
proxy = (Animal) Proxy.newProxyInstance(animal.getClass()
.getClassLoader(), animal.getClass().getInterfaces(), ihz);
proxy.shout();
估计说的不太明白,看看例子也许会明白些
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯