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

参考: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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值