1. 程式人生 > 其它 >aop,基於jdk的動態代理

aop,基於jdk的動態代理

public class ProxyTest {
    public static void main(String[] args) {
        //建立目標物件
        final Target target = new Target();
        //獲得增強物件
        final Advice advice = new Advice();
        //返回值  就是動態生成的代理物件
        TargetInterface proxy = (TargetInterface)Proxy.newProxyInstance(
        target.getClass().getClassLoader(),
//目標物件載入器 target.getClass().getInterfaces(),//目標物件相同的介面位元組碼物件陣列 new InvocationHandler() { // 呼叫代理物件的任何方法 實質執行的都是invoke方法 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //前置增強 advice.before();
//執行目標方法 Object invoke = method.invoke(target, args); //後置增強 advice.afterReturning(); return invoke; } } ); //呼叫代理物件的方法 proxy.save(); } }