动态代理实际上就是建立一个代理类,对需要被代理的类的方法进行增强,动态代理分为jdk代理和cglib代理,jdk代理的类必须实现一个接口,下面就来看看

//接口
public interface Service {
    void buy(int a);
}

//类

public class ServiceImpl implements Service {

    public void buy(int a) {
        System.out.println("买了一本书,"+a+"元");
    }
}

//代理类
public class Proxy implements InvocationHandler {
    private final ServiceImpl s=new ServiceImpl();

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理开始");
        int n=(Integer)args[0];
        return method.invoke(s,n+10);

}
}

//测试
public class Test {
    public static void main(String[]args){
        final ServiceImpl s=new ServiceImpl();
        Service o=(Service)Proxy.newProxyInstance(s.getClass().getClassLoader(),s.getClass().getInterfaces(), new Test2.Proxy());
        o.buy(15);
    }
}

//结果
//代理开始 
//买了一本书,25元