/Users/lyon/j4p/src/classUtils/gui/CommandLineInterpreter.java

1    package classUtils.gui; 
2     
3    import java.lang.reflect.InvocationTargetException; 
4    import java.lang.reflect.Method; 
5    import java.util.StringTokenizer; 
6     
7     
8    public class CommandLineInterpreter { 
9     
10       public static String getString(String prompt) { 
11           return javax.swing.JOptionPane.showInputDialog(prompt); 
12       } 
13    
14       public static String[] getStrings(String commandLine) { 
15           StringTokenizer st = new StringTokenizer(commandLine, " "); 
16           int n = st.countTokens(); 
17           String s[] = new String[n]; 
18           for (int i = 0; i < n; i++) { 
19               s[i] = st.nextToken(); 
20           } 
21           return s; 
22       } 
23    
24       public static void executeTheCommandLine(String s[]) 
25               throws ClassNotFoundException, InvocationTargetException, 
26               IllegalAccessException, InstantiationException { 
27           String className = s[0]; 
28           Class c = Class.forName(className); 
29           //System.out.println(c); 
30    
31           Method mainMethod = getMainMethod(c); 
32           //System.out.println("mainMethod = " + mainMethod); 
33           String args[][] = new String[1][s.length - 1]; 
34           for (int i = 0; i < args[0].length; i++) { 
35               args[0][i] = s[i + 1]; 
36               //System.out.println("args["+i+"]="+args[0][i]); 
37           } 
38           mainMethod.invoke(null, args); 
39       } 
40    
41    
42       public static Method getMainMethod(Class c) { 
43           Method ma[] = c.getMethods(); 
44           for (int i = 0; i < ma.length; i++) { 
45               //System.out.println("ma[" + i + "] = " + ma[i].getName()); 
46               if (ma[i].getName().equals("main")) 
47                   return ma[i]; 
48           } 
49           return null; 
50       } 
51    
52       public static void main(String args[]) { 
53           while (true) { 
54               try { 
55                   String s[] = getStrings( 
56                           getString("command:")); 
57                   executeTheCommandLine(s); 
58               } catch (ClassNotFoundException e) { 
59                   System.out.println("ER!"); 
60               } catch (InvocationTargetException e) { 
61               } catch (IllegalAccessException e) { 
62               } catch (InstantiationException e) { 
63               } 
64           } 
65       } 
66    
67   }