生成動態代理類檔案
阿新 • • 發佈:2020-11-07
前言
剛開始知道動態代理的時候,總是覺得這些東西很神奇,神奇的感覺通常源於未知。這裡介紹兩個可以將生成的動態代理類寫入硬碟生成檔案的方法,方便一睹動態代理類的真容。
jdk 動態代理
在main方法中加入如下程式碼即可:
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
會在專案的根目錄下生成資料夾:com.sun.proxy
有的同學加入了這個配置,有可能還是沒有生成動態代理類檔案。這個時候需要你開啟 sun.misc.ProxyGenerator 這個類,找到 saveGeneratedFiles 這個屬性,看看他取的是哪個系統屬性。
private static final boolean saveGeneratedFiles = (Boolean)AccessController.doPrivileged(new GetBooleanAction("sun.misc.ProxyGenerator.saveGeneratedFiles"));
cglib 動態代理
在main方法中加入如下程式碼:
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E:\\project\\test\\cglib");
還有人提的一種方法:
public static void main(String[] args) { byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[]{ISubject.class}); try { FileOutputStream fileOutputStream = new FileOutputStream("E:\\project\\test\\manual_proxy\\$Proxy0.class"); fileOutputStream.write(bytes); } catch (IOException e) { e.printStackTrace(); } }
這個其實就是jdk動態代理生成代理類檔案呼叫的方法,需要注意的是 generateProxyClass() 方法的第二個引數需要是介面,不然你就會發現生成的代理類檔案中會出現 $proxy implements 類,這顯然是不能編譯通過的。