代理模式——動態代理(自己寫一個)
阿新 • • 發佈:2019-01-23
思路
難點:proxy類,它的作用就是幫我們產生代理類。
- 將所有方法程式碼拼接成字串。
- 將生成代理類的程式碼拼接成字串(包含所有方法拼接成的字串)。
- 將此字串寫入檔案中、並使用JavaComplier對它進行編譯。
- 將編譯好的檔案load進記憶體供我們使用,並返回代理例項。
public class Proxy { public static Object newProxyInstance(Class intefc, InvocationHandler handle) throws Exception { String rt = "\r\t" ; String methodStr = "" ; // first we should realize all the methods of the interface Method[] methods = intefc.getMethods(); for (Method m : methods) { methodStr +="public void "+m.getName()+"(){"+rt+ " try{"+rt+ " Method method = "+intefc.getName()+".class.getMethod(\""+m.getName()+"\");" + rt + " handle.invoke(this,method);" +rt+ " }catch(Exception ex){}" +rt+ "}" ; } String clazzStr = "package com.zdp.dynamicProxy;"+rt+ "import java.lang.reflect.Method;"+rt+ "public class $Proxy1 implements "+intefc.getName()+"{"+rt+ " private com.zdp.dynamicProxy.InvocationHandler handle ;"+rt+ " public $Proxy1(InvocationHandler handle){"+rt+ " this.handle=handle;"+rt+ " }"+rt+ " @Override"+rt+ methodStr +rt+ "}"; // write to a java file String uri = "D:/develop_environment/babasport/homework/src/com/zdp/dynamicProxy/$Proxy1.java"; File file = new File(uri) ; FileWriter writer = null ; try { writer = new FileWriter(file); writer.write(clazzStr) ; writer.flush() ; } catch (IOException e) { e.printStackTrace(); }finally{ try { if(writer !=null){ writer.close() ; } } catch (IOException e) { e.printStackTrace(); } } //load the java file, and then create an instance String url="D:/develop_environment/babasport/homework/src/"; URL[] urls = new URL[] {new URL("file:/" + url)}; URLClassLoader urlLoader = new URLClassLoader(urls); Class c = urlLoader.loadClass("com.zdp.dynamicProxy.$Proxy1"); //return the proxy instance Constructor ctr = c.getConstructor(InvocationHandler.class); Object proxyInstance = ctr.newInstance(handle); return proxyInstance; } }