靜態代理和動態代理的區別


靜態代理通常只代理一個類,動態代理是代理一個接口下的多個實現類。
 
靜態代理事先知道要代理的是什么,而動態代理不知道要代理什么東西,只有在運行時才知道。
 
動態代理是實現 JDK 里的 InvocationHandler 接口的 invoke 方法,但注意的是代理的是接口,也就是你的
 
業務類必須要實現接口,通過 Proxy 里的 newProxyInstance 得到代理對象。
 
還有一種動態代理 CGLIB,代理的是類,不需要業務類繼承接口,通過派生的子類來實現代理。通過在運行
時,動態修改字節碼達到修改類的目的。
 
AOP 編程就是基於動態代理實現的,比如著名的 Spring 框架、 Hibernate 框架等等都是動態代理的使用例子。
 
一個JDK動態代理的例子
package com.proxy;

import org.junit.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class ProxyTest {

    @Test
    public void test01(){
        List<String> list = new ArrayList<>();

        List<String> proxyInstance =
                (List<String >)Proxy.newProxyInstance(
                        list.getClass().getClassLoader(),
                        list.getClass().getInterfaces(),
                        new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if(method.getName().equals("add")){
                                    System.out.println("代理執行...");
                                }
                                return method.invoke(list,args);
                            }
                        });

        proxyInstance.add("你好");
        System.out.println(list);
        proxyInstance.get(0);
        System.out.println(list);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM