Design patterns 使用反射的代理设计模式

Design patterns 使用反射的代理设计模式,design-patterns,Design Patterns,我在以下链接中看到了下面给出的代码: 我无法理解以下代码: Animal proxy = (Animal) Proxy.newProxyInstance(realSubject.getClass() .getClassLoader(), realSubject.getClass().getInterfaces(), new AnimalInvocationHandler(realSubject)); 有人可以提供一些资源/指针来帮助我理解,因为我没有做任何关于反射的工作 import java

我在以下链接中看到了下面给出的代码:

我无法理解以下代码:

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();
    }
}

这是什么意思?它使用类加载器和要代理的类的接口创建一个新对象(返回类型)。最后,它创建一个新的AnimalInvocationHandler,然后将其委托(即调用)给代理对象

从-

静态对象newProxyInstance(类加载器、类[]接口、调用处理程序h) 返回指定接口的代理类实例,该接口将方法调用分派给指定的调用处理程序。 “代理”包裹“狮子”并表现得像狮子,即使它不是“狮子”。 最后,这幅图可能会澄清所涉及的关系-

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

它设置了一个对象,
proxy
,该对象实现了Animal,但在源代码中没有实际的类定义。相反,对
proxy
上的任何方法的调用都通过AnimalInvocationHandler.invoke方法进行。这是标准的java.lang.Proxy工具,通常在您有许多非常相似的方法实现时使用(相反,您有一段实现代码,根据调用的方法的不同,执行一些稍微不同的操作)

这里的区别是invoke方法直接传递给底层对象上的匹配方法,没有添加任何有用的行为(我猜它捕获任何异常,但我认为这不是故意的,他们只是为了清晰地讲授而吞下了大量与反射相关的东西)。不过,我想这更像是一个真正的代理


大概的想法是在传递到实际方法之前或之后添加一些行为(即在
m.invoke(realSubject,args);
行之上或之下)-如果他们添加了一条评论,说
//在这里添加额外的行为
或者其他什么,就会更清楚。

你可能想把这条评论与我今天的博文进行比较- static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h) Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.