靜態代理就是有兩個類,一個是被代理類,一個是代理類。
好比java
//這是一個被代理類學生 public class Student implements Person{ public String name; @Override public void sayHello() { System.out.println("hello"); } }
//這是一個靜態代理學生的類 package com.zhulinan.demo1; public class StaticStudentProxy implements Person{ private Person stu; public StaticStudentProxy(Person stu) { this.stu = stu; } @Override public void sayHello() { System.out.println("我是學生代理,學生讓我和你說:"); this.stu.sayHello(); } }
//測試類 import org.junit.Test; public class StudentProxyTest { @Test public void Test(){ Student student = new Student(); StaticStudentProxy staticStudentProxy = new StaticStudentProxy(student); staticStudentProxy.sayHello(); } }
運行結果:
我是學生代理,學生讓我和你說:
hello設計模式
靜態代理,就是代理設計模式的一種最簡單的體現,可是缺點也很明顯,每次有人要代理的時候,都得寫一個靜態代理類,好比說我做爲一個代理,我只能代理學生或者代理老師或者代理工人,可是一個代理對應一個Person的實現。當代理變化的時候,每一個代理類也都得修改代碼。那麼有沒有什麼能夠代理全部Person實現類的方法呢,好比只要你有sayHello方法,我就能夠代理,你有別的方法我也能夠代理,當方法沒有了我就不代理了,之類的功能的方法呢。 這就引出動態代理緩存
動態代理作了什麼?動態代理也是返回一個代理類,這個類能夠根據你傳入的類私人訂製,並且對於哪些方法須要動態代理也能夠私人訂製。既然說到了能夠根據類私人訂製代理,那麼確定要涉及到獲取每一個類的class信息,因此動態代理也就是基於反射實現的。
動態代理基於反射裏的import java.lang.reflect.Proxy;app
//動態代理類 import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicStudentProxy { public Person CreateProxy(Person person){ Person dynamicStudentProxy = (Person) Proxy.newProxyInstance(person.getClass().getClassLoader(), person.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("sayHello")){ System.out.println("(代理人內心想:發現被代理類要sayHello,這是個人工做我得幫他說)"); System.out.println("我是學生代理,學生讓我和你說:"); return method.invoke(person,args); } return method.invoke(person,args); } }); return dynamicStudentProxy; } }
//測試類 import org.junit.Test; public class StudentProxyTest { @Test public void Test(){ Student student = new Student(); StaticStudentProxy staticStudentProxy = new StaticStudentProxy(student); staticStudentProxy.sayHello(); } @Test public void TestDynamicProxy(){ Person student = new Student(); DynamicStudentProxy dynamicStudentProxy = new DynamicStudentProxy(); Person studentProxy = dynamicStudentProxy.CreateProxy(student); studentProxy.sayHello(); } }
運行結果:
(代理人內心想:發現被代理類要sayHello,這是個人工做我得幫他說)
我是學生代理,學生讓我和你說:
helloide
宏觀角度說,咱們看到一個代理類生成了一個學生的代理,生成過程當中用到了被代理類的類加載器、接口還有一個叫InvocationHandler()的東西。InvocationHandler()這個類的實現能夠看出來就是這個類在被代理類調用方法的時候進行了處理。也就是說student調用方法的時候,處理器InvocationHandler(),會對每一個方法進行攔截,而後檢查這個方法是否是我須要代理的方法,是就作我該作的事情以後再調用原方法,不是的話直接調用原方法。這樣作確實作到了動態代理。函數
那麼JDK動態代理代碼層面是怎麼實現的呢?測試
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { Objects.requireNonNull(h); final Class<?>[] intfs = interfaces.clone(); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkProxyAccess(Reflection.getCallerClass(), loader, intfs); } /* * Look up or generate the designated proxy class. */ Class<?> cl = getProxyClass0(loader, intfs); /* * Invoke its constructor with the designated invocation handler. */ try { if (sm != null) { checkNewProxyPermission(Reflection.getCallerClass(), cl); } final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { cons.setAccessible(true); return null; } }); } return cons.newInstance(new Object[]{h}); } catch (IllegalAccessException|InstantiationException e) { throw new InternalError(e.toString(), e); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw new InternalError(t.toString(), t); } } catch (NoSuchMethodException e) { throw new InternalError(e.toString(), e); } }
重點看這三句:
Class<?> cl = getProxyClass0(loader, intfs);
final Constructor<?> cons = cl.getConstructor(constructorParams);
cons.newInstance(new Object[]{h});
根據源碼註釋,能夠知道第一句生成了一個代理類,後兩句使用這個代理類的構造函數生成了一個具體的對象,而後這個對象返回,也就是咱們上面測試類中獲得的代理類。並且這個構造函數是傳入的參數是h,也就是調用處理器。ui
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) { if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } // If the proxy class defined by the given loader implementing // the given interfaces exists, this will simply return the cached copy; // otherwise, it will create the proxy class via the ProxyClassFactory return proxyClassCache.get(loader, interfaces); }
從註釋能夠看出,若是這個代理類已經加載過了就從緩存中返回一份,若是沒有就使用ProxyClassFactory去建立一份this
/** * A factory function that generates, defines and returns the proxy class given * the ClassLoader and array of interfaces. */ private static final class ProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>> { // prefix for all proxy class names private static final String proxyClassNamePrefix = "$Proxy"; // next number to use for generation of unique proxy class names private static final AtomicLong nextUniqueNumber = new AtomicLong(); @Override public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) { Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length); for (Class<?> intf : interfaces) { /* * Verify that the class loader resolves the name of this * interface to the same Class object. */ Class<?> interfaceClass = null; try { interfaceClass = Class.forName(intf.getName(), false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != intf) { throw new IllegalArgumentException( intf + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. */ if (!interfaceClass.isInterface()) { throw new IllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. */ if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { throw new IllegalArgumentException( "repeated interface: " + interfaceClass.getName()); } } String proxyPkg = null; // package to define proxy class in int accessFlags = Modifier.PUBLIC | Modifier.FINAL; /* * Record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. Verify that * all non-public proxy interfaces are in the same package. */ for (Class<?> intf : interfaces) { int flags = intf.getModifiers(); if (!Modifier.isPublic(flags)) { accessFlags = Modifier.FINAL; String name = intf.getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } else if (!pkg.equals(proxyPkg)) { throw new IllegalArgumentException( "non-public interfaces from different packages"); } } } if (proxyPkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; } /* * Choose a name for the proxy class to generate. */ long num = nextUniqueNumber.getAndIncrement(); String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * Generate the specified proxy class. */ byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try { return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { /* * A ClassFormatError here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded). */ throw new IllegalArgumentException(e.toString()); } } }
byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags);
這裏生成了一個代理類字節碼文件,將這字節碼文件保存到本地,而後反編譯就能夠看到這個生成得代理類spa
public final String sayHello() { try { return (String)this.h.invoke(this, m3, null); } catch (Error|RuntimeException localError) { throw localError; } catch (Throwable localThrowable) { throw new UndeclaredThrowableException(localThrowable); } }
這裏調用sayHello的時候,首先調用了h屬性裏的invoke方法,h實際上是生成代理類父類Proxy的一個屬性:
protected Proxy(InvocationHandler h) { Objects.requireNonNull(h); this.h = h; }
那麼一切均可以解釋了: 生成的代理類中調用的方法都會使用h.invoke調用,傳入參數和函數,讓invoke決定怎麼調用