/Users/lyon/j4p/src/classUtils/reflection/ReflectUtil.java

1    package classUtils.reflection; 
2     
3    import java.lang.reflect.Method; 
4    import java.util.Vector; 
5     
6    /** 
7     * ReflectUtil shows several examples of using 
8     * reflection. 
9     */ 
10   public class ReflectUtil { 
11       private Class c; 
12       private Object o; 
13       public MethodList ml; 
14    
15       /** 
16        * Instance the ReflectUtil with an Object. 
17        * ReflectUtils gives extra feature not 
18        * available with reflection. 
19        * 
20        * @param _o an instance of an object to be 
21        *           inspected 
22        */ 
23       public ReflectUtil(Object _o) { 
24           c = _o.getClass(); 
25           o = _o; 
26           ml = new MethodList(c); 
27       } 
28    
29       /** 
30        * Get a list of all the constructors in the 
31        * containing class. Default constructors can 
32        * be returned. For interfaces and primitive 
33        * data types, no constructor is returned. 
34        * 
35        * @return an array of constructors. 
36        */ 
37       public java.lang.reflect.Constructor[] getConstructors() { 
38           return 
39                   c.getDeclaredConstructors(); 
40       } 
41    
42       /** 
43        * Get all but the inherited fields. 
44        * 
45        * @return array of field instances. 
46        */ 
47       public java.lang.reflect.Field[] getFields() { 
48           return c.getDeclaredFields(); 
49       } 
50    
51       /** 
52        * Get all but inherited methods. 
53        * 
54        * @return array of methods 
55        */ 
56       public java.lang.reflect.Method[] getMethods() { 
57           return c.getDeclaredMethods(); 
58       } 
59    
60       public Method[] getAllPublicStaticMethods() { 
61           return ml.getAllPublicStaticMethods(); 
62       } 
63    
64       public void printDeclaredMethods() { 
65           Method m[] = c.getDeclaredMethods(); 
66           for (int i = 0; i < m.length; i++) 
67               System.out.println(m[i].toString()); 
68       } 
69    
70       public Method[] getAllPublicMethods() { 
71           return ml.getAllPublicMethods(); 
72       } 
73    
74       /** 
75        * Obtain a list of all the methods. 
76        * 
77        * @return an array of all methods (including 
78        *         super classes). 
79        */ 
80       public java.lang.reflect.Method[] getAllMethods() { 
81           return ml.getMethods(); 
82       } 
83    
84    
85       /** 
86        * Returns true if the <code>Class</code> has 
87        * a <code>public static void main(String 
88        * args[])</code> method in it. 
89        * 
90        * @return <code>true</code> if and only if 
91        *         class has a main. 
92        */ 
93       public static boolean hasMain( 
94               Class classToBeExamined) { 
95           ReflectUtil ru = new ReflectUtil( 
96                   classToBeExamined); 
97           Method m[] = ru.getAllPublicStaticMethods(); 
98           for (int i = 0; i < m.length; i++) 
99               System.out.println("method:" + m[i]); 
100          return true; 
101      } 
102   
103   
104      public Class[] getSuperClasses() { 
105          Class sc = c; 
106          Vector v = new Vector(); 
107          v.addElement(c); 
108          while ((sc = sc.getSuperclass()) != null) 
109              v.addElement(sc); 
110          Class ca[] = new Class[v.size()]; 
111          v.copyInto(ca); 
112          return ca; 
113      } 
114   
115      public Class[] getSuperInterfaces(Class ca[]) { 
116          Vector v = new Vector(); 
117          for (int i = 0; i < ca.length; i++) { 
118              Class newArray[] = 
119                      getSuperInterfaces(ca[i]); 
120              for (int j = 0; 
121                   j < newArray.length; 
122                   j++) 
123                  v.addElement(newArray[j]); 
124          } 
125          Class rc[] = new Class[v.size()]; 
126          v.copyInto(rc); 
127          return rc; 
128      } 
129   
130      /** 
131       * Get all the interfaces implemented by this 
132       * class, in order of listing. 
133       * 
134       * @param ci class instance to be inspected 
135       * @return an array of all the classes that 
136       *         correspond to the interfaces. 
137       */ 
138      public static Class[] getSuperInterfaces( 
139              Class ci) { 
140          return ci.getInterfaces(); 
141      } 
142   
143      /** 
144       * Get a list of public class members that are 
145       * not inherited. 
146       * 
147       * @return an array of Class class instances. 
148       */ 
149      public Class[] getPublicClassMembers() { 
150          return c.getClasses(); 
151      } 
152      public static Class[] getAllInterfaces(Class c) { 
153          Vector v = new Vector(); 
154          Class ca[] = c.getInterfaces(); 
155          for (int i=0; i < ca.length;i++) 
156              addImmediateInterfaces(ca[i],v); 
157          Class ca2 [] = new Class[v.size()]; 
158          v.copyInto(ca2); 
159          return ca2; 
160      } 
161      public static void addImmediateInterfaces(Class c, Vector v) { 
162          v.addElement(c); 
163           Class ca[] = c.getInterfaces(); 
164          for (int i=0; i < ca.length;i++) 
165              v.addElement(ca[i]); 
166      } 
167      public String[] getReadMethodNames() { 
168          java.lang.reflect.Method m[] = getMethods(); 
169          java.util.Vector v = new java.util.Vector(); 
170          for (int i = 0; i < m.length; i++) { 
171              String s = getName(m[i]); 
172              if (s.startsWith("get") || 
173                  s.startsWith("is")) { 
174                  v.addElement(s); 
175                  System.out.println(s); 
176              } 
177          } 
178          String getterArray[] = new String[v.size()]; 
179          v.copyInto(getterArray); 
180          return getterArray; 
181      } 
182      
183      /** 
184        * Get the method that have exactly n arguments 
185        * @param n a number that start at 0 
186        * @return returns the read method array 
187        */ 
188       public String[] getReadPublicMethodNames(int n) { 
189           java.lang.reflect.Method m[] = getMethodsWithNArgs( 
190                   n); 
191           return getReadMethodNames(m); 
192       } 
193   
194      /** 
195       * Get the method that have exactly n arguments 
196       * @param n a number that start at 0 
197       * @return returns the read method array 
198       */ 
199      public String[] getReadMethodNames(int n) { 
200          java.lang.reflect.Method m[] = getMethodsWithNArgs( 
201                  n); 
202          return getReadMethodNames(m); 
203      } 
204   
205      private String[] getReadMethodNames( 
206              java.lang.reflect.Method[] m) { 
207          Vector v = new Vector(); 
208          for (int i = 0; i < m.length; i++) { 
209              String s = getName(m[i]); 
210              if (s.startsWith("get") || 
211                  s.startsWith("is")) 
212                  v.addElement(s); 
213          } 
214          String getterArray[] = new String[v.size()]; 
215          v.copyInto(getterArray); 
216          return getterArray; 
217      } 
218   
219      /** 
220       * @return method in present class 
221       */ 
222      public String[] getWriteMethodNames() { 
223          java.lang.reflect.Method m[] = getMethods(); 
224          return getWriteMethodNames(m); 
225      } 
226   
227      public String[] getWriteMethodNames( 
228              java.lang.reflect.Method[] m) { 
229          Vector v = new Vector(); 
230          for (int i = 0; i < m.length; i++) { 
231              String s = getName(m[i]); 
232              if (s.startsWith("set")) { 
233                  v.addElement(s); 
234                  System.out.println(s); 
235              } 
236          } 
237          String setterArray[] = new String[v.size()]; 
238          for (int i = 0; 
239               i < setterArray.length; 
240               i++) 
241              setterArray[i] = 
242              (String) v.elementAt(i); 
243          return setterArray; 
244      } 
245   
246      /** 
247       * @param s a method name 
248       * @return a method that corresponds to this 
249       *         name 
250       */ 
251      public java.lang.reflect.Method getMethod( 
252              String s) { 
253          java.lang.reflect.Method m = null; 
254          try { 
255              m = c.getMethod(s, new Class[]{}); 
256          } catch (NoSuchMethodException e) { 
257              System.out.println(e); 
258          } 
259          return m; 
260      } 
261   
262      /** 
263       * invoke a methodName string with no 
264       * arguments. 
265       */ 
266      public Object invoke(String methodName) { 
267          java.lang.reflect.Method m = getMethod( 
268                  methodName); 
269          Object ret = null; 
270          try { 
271              ret = m.invoke(o, null); 
272          } catch (java.lang.reflect.InvocationTargetException e) { 
273              e.printStackTrace(); 
274          } catch (IllegalAccessException e) { 
275              e.printStackTrace(); 
276          } 
277          return ret; 
278      } 
279   
280      /** 
281       * @param m a method to be inspected 
282       * @return modifiers encoded as an int. 
283       */ 
284      public int getModifiers( 
285              java.lang.reflect.Method m) { 
286          return m.getModifiers(); 
287      } 
288   
289      /** 
290       * @param m method 
291       * @return a string representation of the 
292       *         modifiers 
293       */ 
294      public String getModifierString( 
295              java.lang.reflect.Method m) { 
296          return java.lang.reflect.Modifier.toString( 
297                  getModifiers(m)); 
298      } 
299   
300      /** 
301       * Print an array of objects. 
302       * 
303       * @param o an array, printed one element per 
304       *          line. 
305       */ 
306      public static void println(Object o[]) { 
307          for (int i = 0; i < o.length; i++) 
308              System.out.println(o[i]); 
309      } 
310   
311      /** 
312       * Convert an array of <code>Object</code> 
313       * into a string. 
314       * 
315       * @param o an array of string in 
316       * @return a big string with new lines out 
317       */ 
318      public static String toString(Object o[]) { 
319          String s = ""; 
320          for (int i = 0; i < o.length; i++) 
321              s = s + o[i] + "\n"; 
322          return s; 
323      } 
324   
325      /** 
326       * print information about the containing 
327       * instance to the console. 
328       */ 
329      public void printInfo() { 
330          System.out.println( 
331                  "Info on class " + 
332                  getClassName()); 
333          System.out.println("Constructors:"); 
334          println(getConstructors()); 
335          System.out.println("Fields:"); 
336          println(getFields()); 
337          System.out.println("Methods:"); 
338          println(getMethods()); 
339          System.out.println( 
340                  "Methods with 0 arguments"); 
341          println(getMethodsWithNArgs(0)); 
342          System.out.println("read methods"); 
343          println(getReadMethodNames()); 
344          System.out.println("write methods"); 
345          println(getWriteMethodNames()); 
346          System.out.println("Classes"); 
347          println(getPublicClassMembers()); 
348      } 
349   
350      /** 
351       * Get the name of the containing class. 
352       * 
353       * @return classname. 
354       */ 
355      public String getClassName() { 
356          return c.getName(); 
357      } 
358   
359      java.lang.reflect.Method[] getMethodsWithNArgs( 
360              int n) { 
361          java.lang.reflect.Method m[] = getMethods(); 
362          java.util.Vector v = new java.util.Vector(); 
363          for (int i = 0; i < m.length; i++) { 
364              Class ca[] = m[i].getParameterTypes(); 
365              if (ca.length == n) 
366                  v.addElement(m[i]); 
367          } 
368          java.lang.reflect.Method ma[] = new java.lang.reflect.Method[v.size()]; 
369          v.copyInto(ma); 
370          return ma; 
371      } 
372   
373      /** 
374       * Get A string representation of the method. 
375       * 
376       * @param m method name 
377       * @return the name of the method 
378       */ 
379      public String getName( 
380              java.lang.reflect.Method m) { 
381          return m.getName(); 
382      } 
383   
384      public String getInfoString( 
385              java.lang.reflect.Method m) { 
386          return 
387                  "for method " + m.getName() + 
388                  "\nThe modifier = " + 
389                  getModifierString(m) + 
390                  "\nThe return type =" + 
391                  m.getReturnType().getName() + 
392                  "\n The arguments for this method are " + 
393                  toString(m.getParameterTypes()); 
394      } 
395   
396      public void printInfo( 
397              java.lang.reflect.Method m) { 
398          System.out.println(getInfoString(m)); 
399      } 
400   
401   
402      /** 
403       * Example of reflectUtil usage. 
404       * 
405       * @param args ignored. 
406       */ 
407      public static void main(String args[]) { 
408      } 
409   
410      private static void testGetInfo() { 
411          //Object f = new SimpleClass(); 
412          Object f = new java.util.Date(); 
413          ReflectUtil ru = new ReflectUtil(f); 
414          //ru.println( 
415          //        ru.getSuperInterfaces(ru.getSuperClasses())); 
416          //ru.println(ru.getSuperClasses()); 
417          //ru.getMainMethods(); 
418          String getterNames[] 
419                  = ru.getReadMethodNames(0); 
420          // for (int i=0; i < getterNames.length; i++) 
421          //  System.out.println( 
422          //      getterNames[i]+"=" 
423          //          + ru.invoke(getterNames[i])); 
424          // 
425   
426          //ru.startCommandLineInterpreter(); 
427          ru.printInfo(); 
428      } 
429   
430      /** 
431       * starts a simple command line interpreter 
432       * that takes in method names. 
433       */ 
434      public void startCommandLineInterpreter() { 
435          String s = null; 
436          String prompt = "enter command:"; 
437          while (!(s = getString(prompt)).startsWith( 
438                  "quit")) 
439              try { 
440                  prompt = s + "=" + invoke(s); 
441              } catch (Exception e) { 
442                  prompt = e.toString(); 
443              } 
444          ; 
445      } 
446   
447      public static String getString(String prompt) { 
448          return javax.swing.JOptionPane.showInputDialog( 
449                  prompt); 
450      } 
451   
452      /** 
453       * Get the containing class class instance. 
454       * 
455       * @return The containing class class. 
456       */ 
457      public Class getC() { 
458          return c; 
459      } 
460  } 
461   
462   
463