/Users/lyon/j4p/src/bookExamples/ch24Reflection/Ex3.java
|
1 package bookExamples.ch24Reflection;
2
3 import gui.In;
4
5 import java.util.StringTokenizer;
6 import java.lang.reflect.Method;
7 import java.lang.reflect.InvocationTargetException;
8
9 /**
10 * DocJava, Inc.
11 * http://www.docjava.com
12 * Programmer: dlyon
13 * Date: Oct 6, 2004
14 * Time: 8:33:48 PM
15 */
16 public class Ex3 {
17 // prompt the user for a class name that has a main
18 // method
19 public static void main(String[] args) {
20 try {
21 executeMainCli();
22 } catch (ClassNotFoundException e) {
23 e.printStackTrace();
24 } catch (NoSuchMethodException e) {
25 e.printStackTrace();
26 } catch (IllegalAccessException e) {
27 e.printStackTrace();
28 } catch (InvocationTargetException e) {
29 e.printStackTrace();
30 }
31 }
32
33 private static void executeMainCli() throws
34 ClassNotFoundException,
35 NoSuchMethodException,
36 IllegalAccessException,
37 InvocationTargetException {
38 String className = In.getString("enter a class name that has a main");
39 String arguments = In.getString("enter the arguments for the main method");
40 String argsArray[] = getArray(arguments);
41 Class c = Class.forName(className);
42 Class parameterType = argsArray.getClass();
43 // this is the part you do for homework!;
44 String name = "noArgs"; // alter this so it has args and uses main.
45 Method main = c.getMethod(name, new Class[]{});
46 main.invoke(null,null);
47
48 }
49 private static String [] getArray(String s) {
50 StringTokenizer st = new StringTokenizer(s);
51 int n = st.countTokens();
52 String sa[] = new String[n];
53 for (int i=0; i < n; i++)
54 sa[i] = st.nextToken();
55 return sa;
56 }
57 }
58