动态代理

2020-01-20  本文已影响0人  茶酒qqq

动态代理

基于接口的动态代理

main方法:

final Producer producer=new Producer();

IProducer proxy=(IProducer) Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(), new InvocationHandler() {
    /**
     *
     * @param proxy 代理对象的引用
     * @param method 当前执行的被代理对象的方法
     * @param args 当前方法的参数
     * @return 和被代理对象方法返回值相同
     * @throws Throwable
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            Float money=(Float)args[0];
            Object rtValue=null;
            if(method.getName().equals("saleService")) {
                rtValue = method.invoke(producer, money * 0.8f);
            }
            return rtValue;

    }
});

proxy.saleService(10000f);

基于子类的动态代理

final Producer producer=new Producer();

Producer proxy=(Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
    /**
     *
     * @param o
     * @param method
     * @param objects
     * @param methodProxy
     * @return
     * @throws Throwable
     */
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Float money=(Float)objects[0];
        Object rtValue=null;
        if(method.getName().equals("saleService")) {
            rtValue = method.invoke(producer, money * 0.8f);
        }
        return rtValue;
    }
});

proxy.saleService(10000f);
上一篇 下一篇

猜你喜欢

热点阅读