1. 程式人生 > >java反射之動態代理學習筆記

java反射之動態代理學習筆記

ace ins 功能 運行 invoke -- ram lang glib

動態代理概述:
代理:本來自己做的事情,請別人來做,被請的人就是代理對象;
舉例:春節回家買票讓人代理買
動態代理:在程序運行過程中產生的這個對象,而程序運行過程中產生對象其實就是我們剛才反射講解的內容,所以動態代理其實就是通過反射來生成一個代理。
在java 中java.lang.reflect包提供一個proxy類和一個invocationHandler接口,通過使用這個類和接口就可以生成動態代理對象,JDk提供代理只能針對接口做代理,我們有更強大的代理cglib、proxy類中的方法創建動態代理對象。
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces, InvocationHandler h)

測試方法一

/**
     * @param args
     */
    public static void main(String[] args) {
        /*UserImp ui = new UserImp();
        ui.add();
        ui.delete();

        System.out.println("-------------------------------");*/
        /*
         * public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,
         * InvocationHandler h)
         */
        /*MyInvocationHandler m = new MyInvocationHandler(ui);
        User u = (User)Proxy.newProxyInstance(ui.getClass().getClassLoader(), ui.getClass().getInterfaces(), m);
        u.add();
        u.delete();*/

        StudentImp si = new StudentImp();
        si.login();
        si.submit();

        System.out.println("-------------------------------");
        MyInvocationHandler m = new MyInvocationHandler(si);
        Student s = (Student)Proxy.newProxyInstance(si.getClass().getClassLoader(), si.getClass().getInterfaces(), m);

        s.login();
        s.submit();
    }

方法二

public interface User {
    public void add();

    public void delete();
}

方法三

public class UserImp implements User {

    @Override
    public void add() {
        //System.out.println("權限校驗");
        System.out.println("添加功能");
        //System.out.println("日誌記錄");
    }

    @Override
    public void delete() {
        //System.out.println("權限校驗");
        System.out.println("刪除功能");
        //System.out.println("日誌記錄");
    }

}

方法四


public class StudentImp implements Student {

    @Override
    public void login() {
        System.out.println("登錄");
    }

    @Override
    public void submit() {
        System.out.println("提交");
    }

}

方法五

public interface Student {
    public void login();

    public void submit();
}

方法六

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        System.out.println("權限校驗");
        method.invoke(target, args);                    //執行被代理target對象的方法
        System.out.println("日誌記錄");
        return null;
    }

}

java反射之動態代理學習筆記