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