第一种JDK的方式(需要一个接口和接口实现类)
接口类
public interface Producer {
public double getMoney(double money);
}
实现类
public class ProducerImpl implements Producer{
@Override
public double getMoney(double money) {
return money;
}
}
测试类(生成代理类)
public class ProxyProdeucerImpl {
public static void main(String[] args) {
final Producer producer = new ProducerImpl();
//三个参数
//任意类加载器 原始类实现了的接口 代理实现
Producer proxy=(Producer)Proxy.newProxyInstance(Producer.class.getClassLoader(), a ProducerImpl.class.getInterfaces(), new InvocationHandler() {
@Override
//代理对象 方法 方法参数
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result=null;
if("getMoney".equals(method.getName())){
System.out.println("前置通知");
result = method.invoke(producer,(double)args[0]*(0.8));
System.out.println("后置通知");
}
return result;
}
});
double money = proxy.getMoney(1000);
System.out.println(money);
}
}
基于CGlib的方式(不需要接口类,直接继承原始类)
原始类
public class Customer {
public int getMoney(int money) {
System.out.println(money);
return money;
}
}
测试类
public class ProyCustomer {
public static void main(String[] args) {
Customer customer = new Customer();
//类字节码文件,原始类的方法,callback接口(methodInterceptor)一致
Customer o =(Customer) Enhancer.create(Customer.class, Customer.class.getInterfaces(),new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy)throws Throwable {
Object result = null;
System.out.println("前置通知");
result = method.invoke(customer, objects);
System.out.println("后置通知");
return result;
}
});
o.getMoney(1000);
}
}