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

靜態代理一般只代理一個類,動態代理是代理一個接口下的多個實現類。
 
靜態代理事先知道要代理的是什麼,而動態代理不知道要代理什麼東西,只有在運行時才知道。
 
動態代理是實現 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);
    }

}
相關文章
相關標籤/搜索