//檔名:Run.java //說明:本程式可以直接執行應用程式(application)與小程式(applet) import java.io.*; import java.awt.*; import javax.swing.*; import java.lang.reflect.Method; import java.util.StringTokenizer; public class Run extends ClassLoader { static String 類別名稱=null; static String[] 參數陣列=null; public static void main(String[] 參數) { Run 載入器 = new Run(); if (參數.length<1) { Frame 虛設窗框=new Frame(); FileDialog 檔案對話框=new FileDialog(虛設窗框,"請選擇位元組碼(bytecode)檔案"); 檔案對話框.setFile("*.class"); 檔案對話框.setVisible(true); String 檔名=檔案對話框.getFile(); if(檔名==null) { System.out.println("請於檔案對話框中選擇類別之位元組碼檔案,或使用以下之用法:\n\n"+ "java Run 類別名稱 參數1 參數2 ...\n 或\n"+ "jr 類別名稱 參數1 參數2 ..."); System.exit(0); } //敘述:if 區塊結束 String 目錄=檔案對話框.getDirectory(); if (目錄.endsWith(System.getProperty("file.separator"))) 目錄=目錄.substring(0,目錄.length()-1); String 目前目錄=System.getProperty("user.dir"); if (!目錄.equals(目前目錄)) { System.out.println("類別之位元組碼檔案必須位於目前工作目錄下"); System.exit(0); } 類別名稱=檔名.substring(0,檔名.length()-6); System.out.print(類別名稱); String 輸入參數=JOptionPane.showInputDialog(null,"請輸入命令列參數","輸入命令列參數",JOptionPane.QUESTION_MESSAGE); if (輸入參數!=null) { StringTokenizer 字串記號 = new StringTokenizer(輸入參數); int 記號個數=字串記號.countTokens(); 參數陣列=new String[記號個數]; int i=0; while (字串記號.hasMoreTokens()) 參數陣列[i++]=字串記號.nextToken(); for(i=0;i<參數陣列.length;++i) System.out.print(" "+參數陣列[i]); System.out.println(); } else System.out.println(); //(輸入參數==null) } //敘述:if 區塊結束 else { //以下表示有命令列參數 類別名稱=參數[0]; int 參數個數 = 參數.length-1; 參數陣列= new String[參數個數]; if (參數個數>0) System.arraycopy(參數, 1 , 參數陣列, 0, 參數個數); } try { Class 類別物件= 載入器.loadClass(類別名稱); Class[] 參數類別 = new Class[1]; 參數類別[0]= 參數.getClass(); Method 方法物件=null; try{方法物件= 類別物件.getMethod("main", 參數類別);} catch(NoSuchMethodException 例外) { 執行小程式(類別名稱); System.exit(0); } Object[] 參數物件陣列= new Object[1]; 參數物件陣列[0]=參數陣列; 方法物件.invoke(null, 參數物件陣列); System.exit(0); } catch (Exception 例外) { 例外.printStackTrace(); System.exit(1); } } //方法:main() 定義區塊結束 public static void 執行小程式(String 類別名稱) throws IOException { String 臨時檔名=類別名稱+"網頁.html"; String 檔案內容字串="\r\n\r\n\r\n"; char[] 緩衝區=new char[檔案內容字串.length()]; 檔案內容字串.getChars(0,檔案內容字串.length(),緩衝區,0); BufferedWriter 寫入 = new BufferedWriter(new FileWriter(臨時檔名)); 寫入.write(緩衝區); 寫入.close(); Process 程序=Runtime.getRuntime().exec("appletviewer "+臨時檔名); InputStreamReader 讀出= new InputStreamReader(程序.getInputStream()); int 字元; String 字串=""; while ((字元=讀出.read()) !=-1) 字串+=(char)字元; System.out.print(字串); System.exit(0); } //方法:執行小程式 定義區塊結束 //以下改寫(override) loadClass(String)方法 public Class loadClass(String 類別名稱) throws ClassNotFoundException { Class 類別物件=null; try { 類別物件=findSystemClass(類別名稱); } catch (ClassNotFoundException 例外){ System.out.println("找不到類別: "+類別名稱); System.out.println("(類別之位元組碼檔案必須位於目前工作目錄下)"); System.exit(1); } finally {return 類別物件;} } //方法:loadClass() 定義區塊結束 } //類別:Run 定義區塊結束