在網上學習了馬士兵老師的設計模式視屏,過程中也有認真的做相應的筆記。在次分享我的一些
成果,方便大家的進一步學習。
1、接口
1 public interface Moveable { 2 void move(); 3 }
2、被代理的對象
1 public class Tank implements Moveable { 2 3 @Override 4 public void move() { 5 6 System.out.); 7 try { 8 Thread.sleep(new Random().nextInt(10000)); 9 } catch (InterruptedException e) {10 e.printStackTrace();11 }12 13 }14 15 }
3、測試主類
1 public class Test { 2 public static void main(String[] args) throws Exception{ 3 String rt = "/r/n"; 4 5 //代理類的字符串代碼 6 String src = 7 "public class TankTimeProxy implements Moveable {"+rt+ 8 " Moveable t;"+rt+ 9 10 " public TankTimeProxy(Moveable t) {"+rt+11 " this.t = t;"+rt+12 " }"+rt+13 14 " @Override"+rt+15 " public void move() {"+rt+16 " long start = System.currentTimeMillis();"+rt+17 " System.out.println(/"start time is /"+start);"+rt+18 " t.move();"+rt+19 " long end = System.currentTimeMillis();"+rt+20 " System.out.println(/"end time is /"+end);"+rt+21 " System.out.println(/"time is /"+(end - start));"+rt+22 " }"+rt+23 "}";24 25 //將字符串寫入java文件********************************************************************************26 String fileName = System.getProperty("user.dir")+"/src/TankTimeProxy.java";//放置在(根目錄+文件名)下27 File f = new File(fileName);28 FileWriter fw = new FileWriter(f);29 //寫入內容30 fw.write(src); 31 fw.flush();32 fw.close();33 34 //進行編譯********************************************************************************************35 //首先獲得編譯器36 //compiler 為java編譯器 即javac37 //獲得編譯器對象38 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();39 40 //參數含義 (編譯診斷,locale,charset)41 //管理動態生成的文件的StandardJavaFileManager對象42 StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,null,null);//默認值43 44 //根據參數獲取多個java文件 返回java文件對象集45 Iterable units = fileManager.getJavaFileObjects(fileName);46 47 //“編譯任務”對象48 JavaCompiler.CompilationTask task = compiler.getTask(null,fileManager,null,null,null,units);49 task.call();//調用50 fileManager.close();51 52 //************以上過程獲得了java文件源碼,編譯java文件生成了相對應的class文件****************53 54 //***************以下過程為將class文件加載至內存,生成新對象*****************************55 //Class.load() 是加載path路徑的class文件56 //URLClassLoader是將硬盤中的class文件加載進入57 58 //通過Url引入本地文件59 URL[] urls = new URL[]{new URL("file:/"+System.getProperty("user.dir")+"/out/production/proxy")}; //訪問本地class文件,這里我用的是IntellijIDEA,默認 生成的class文件的目錄在 /out/production/ 下60 61 62 //去指定路徑尋找class文件63 URLClassLoader urlClassLoader = new URLClassLoader(urls);64 65 Class c = urlClassLoader.loadClass("TankTimeProxy");66 67 System.out.println(c);68 69 //執行70 //c.newInstance(); 是調用空的構造方法71 72 //獲得構造方法73 //根據java虛擬機,每一個構造方法也相當于一個對象74 Constructor constructor = c.getConstructor(Moveable.class);75 76 //產生新對象77 Moveable m = (Moveable) constructor.newInstance(new Tank()); //new Tank()為構造方法的參數 即被代理對象78 79 m.move();80 81 }82 }83 84
4、執行結果
新聞熱點
疑難解答