基于子类的动态代理

Producer类

/**
 * @author rui
 */
public class Producer {
    public void saleProduct(Float money) {
        System.out.println("共" + money + "元");
    }
    public void afterProduct(Float money) {
        System.out.println("售后共" + money + "元");
    }
}

增强方法测试类

package cn.ytmj.test;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
/**
 * 基于子类的动态代理
 *
 * @author rui
 */
public class Test {
    public static void main(String[] args) {
        final Producer producer = new Producer();
        /**
         *Callback:用于提供增强的代码
         *      一般使用改接口的子接口实现类MethodInterceptor
         */
        Producer producer1 = (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 {
                //增强的代码
                Object o1 = null;
                Float money = (Float) objects[0];
                if ("saleProduct".equals(method.getName())) {
                    money = money * 0.8f;        //增强
                    o1 = method.invoke(producer, money);
                }
                return o1;
            }
        });
        producer1.saleProduct(1000F);
    }
}

maven 在pom.xml中加入

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.3.0</version>
        </dependency>
原文地址:https://www.cnblogs.com/PoetryAndYou/p/11517416.html