0

我从以下链接中看到了下面给出的代码:http: //javapapers.com/design-patterns/proxy-design-pattern/

我无法理解以下代码:

Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
.getClassLoader(), realSubject.getClass().getInterfaces(),
new AnimalInvocationHandler(realSubject));

有人可以提供一些资源/指针来帮助我理解,因为我没有做任何关于反思的工作。

import java.lang.reflect.Proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

interface Animal {

    public void getSound();

}

class Lion implements Animal {

    public void getSound() {
        System.out.println("Roar");
    }
}

class AnimalInvocationHandler implements InvocationHandler {

    private Object realSubject = null;

    public AnimalInvocationHandler(Object realSubject) {
        this.realSubject = realSubject;
    }

    public Object invoke(Object proxy, Method m, Object[] args) {
        Object result = null;
        try {
            result = m.invoke(realSubject, args);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }


}

public class ProxyExample {

    public static void main(String[] args) {
        Animal realSubject = new Lion();
        Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass()
                .getClassLoader(), realSubject.getClass().getInterfaces(),
                new AnimalInvocationHandler(realSubject));
        proxy.getSound();
    }
}
4

2 回答 2

0

部分问题可能是,正如所写,它似乎没有做任何非常有用的事情:-)

它设置了一些东西,以便您拥有一个proxy实现 Animal 的对象,但在您的源代码中没有可见的实际类定义。相反,对任何方法的调用proxy都会通过 AnimalInvocationHandler.invoke 方法。这是标准的 java.lang.Proxy 东西,通常在您有许多非常相似的方法实现时使用(相反,您有一段实现代码,根据调用的方法做一些稍微不同的事情)。

这里的不同之处在于,invoke 方法直接传递到底层对象上的匹配方法,没有添加任何有用的行为(我猜它会捕获任何异常,但我认为这不是故意的,它们只是吞下了大量与反射相关的东西为了教学清晰)。不过,我想这使它更像是一个真正的代理。

大概的想法是,您将在传递给真实方法之前或之后添加一些行为(即m.invoke(realSubject, args);在行的上方或下方)-如果他们添加了评论// add extra behaviour here或其他内容,则会更清楚。

于 2013-11-29T16:31:26.473 回答
0

这意味着什么?它使用要代理的类的 ClassLoader 和 Interfaces 创建一个新的 Object(返回类型)。最后,它创建一个新的 AnimalInvocationHandler,然后委托(即调用)代理对象。

代理-

静态对象 newProxyInstance(ClassLoader 加载器,Class[] 接口,InvocationHandler h)
     返回将方法调用分派到指定调用处理程序的指定接口的代理类的实例。

“代理”包裹“狮子”并像狮子一样行事,即使它不是“狮子”。最后,也许这张照片会澄清所涉及的关系——

于 2013-11-15T07:07:45.900 回答