//一、聲明一段源碼,動態產生代理 //windows系統中的回車換行符\r\n String rt = "\r\n"; String methodStr=""; for(Method m : infce.getMethods()) { methodStr += " @Override"+rt+ " public void " + m.getName() +"() {"++ " try{"+rt+ " Method md = "+infce.getName+".class.getMethod(\""+m.getName()+"\""+rt+ " h.invoke(this,md);"+rt+ " }catch(Exception e){e.printStackTra();}"+rt+ "}"; } String str= "package com.imooc.proxy;"+rt+ "import java.lang.reflect.Method;"+rt+ "import com.imooc.proxy.InvocationHandler+rt+ "public class $Proxy0 implements+infce.getName()+ " {"+rt+ " public $Proxy0(InvocationHandler h) +rt+ " this.h = h;"+rt+ "}"+rt+ " private InvocationHandler h;"+rt+ methodStr+rt+ "}";
//產生代理類的Java文件 String filename = System.getProperty("user.dir")+"/bin/com/imooc/proxy/$Proxy0.java"; File file = new File(filename); FileUtils.writeStringToFile(file, str);
JavaCompiler comproiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = comproiler.getStandardFileManager(null, null, null);
Iterable units = fileManager.getJavaFileObjects(file);
CompilationTask task = comproiler.getTask(null, fileManager, null, null, null, units);
task.call();
fileManager.close();
//由於生成的文件在bin目錄下,能夠直接使用ClassLoader進行加載 ClassLoader cl = ClassLoader.getSystemClassLoader(); //默認生成的代理類名稱均爲 $Proxy0 Class c = cl.loadClass("com.imooc.proxy.$Proxy0");
//獲取類的構造函數,建立類的實例 Constructor ctr = c.getConstructor(InvocationHandler.class); return ctr.newInstance(h);
建立一個InvocationHandler(專門作事務處理)java
Car car = new Car(); InvocationHandler h = new TimeHandler(car); Moveable m = (Moveable) Proxy.newProxyInstance(Moveable.class,h); m.move();