java____设计模式之动态代理模式

来源:互联网 发布:java培训班能就业吗 编辑:程序博客网 时间:2024/04/29 14:39

参考:http://www.infoq.com/cn/articles/cf-java-reflection-dynamic-proxy

每次学习到设计模式都是从源码中get到的新东西。

很早之前看过书,当时感觉设计模式好完美,开阔了我的视野。当我深入理解了我就是想说:卧槽,好牛逼。

上面都是扯淡,那我们就开始咯。

我们记住一些话:(重要)
1.代理对象和被代理对象一般实现相同的接口,调用者与代理对象进行交互。

2.
ivvocationHandler
invoke方法的参数中可以获取到代理对象,
———->方法对应的Method对象和调用的实际参数。
这种做法实际相当于对当前方法进行拦截。

小Demo中一共有三个类。

这里写图片描述

ProxyInterFace

public interface ProxyInterFace {    public int proxyMethod(int age, String sex);}

TargetObject

public class TargetObject implements ProxyInterFace {    @Override    public int proxyMethod(int age, String sex) {        // TODO Auto-generated method stub        //        System.out.println("代理成功了 age="+age+"  sex="+sex);        return 0;    }}

ProxyTest

public class ProxyTest {        static ProxyInterFace proxyInterface;    public static void main(String args[]) throws Exception {        // 代理的目标对象         proxyInterface = new TargetObject();        // 执行代码任务        Object proxy = Proxy.newProxyInstance(proxyInterface.getClass()                .getClassLoader(), proxyInterface.getClass().getInterfaces(),                new InvocationHandler() {                    @Override                    public Object invoke(Object proxy, Method method,                            Object[] args) throws Throwable {                        // 获取                        // method = proxyMethod                        // args [1, sex]                        int a = 1;                        a = a + 1;                        return method.invoke(proxyInterface, args);                    }                });        // 转换成目标对象,调用目标对象的方法        ((ProxyInterFace) proxy).proxyMethod(1, "sex");    }}

其实通过上面的例子,可以看出来我们不需要知道是谁,我们只需要他们的接口是什么。
可以获取:
1.方法名称 ———————–> method.getName()
2.可以获取方法参数———————> 参数实际的值。
3.可以获取方法注解——————->method.getAnnotations();
4.可以返回参数类型数组——–method.getGenericParameteTypes();
5.可以返回参数类型数组注解———–>method.getGenericeParameteTypes();

0 0