KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > tools > common > util > ObjectAnalyzer


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 /**
25  * WBN -- generic mechanism for simulating toString() and equals()
26  * for any class
27  */

28
29 package com.sun.enterprise.tools.common.util;
30
31 import java.lang.reflect.*;
32 import java.util.Vector JavaDoc;
33 import com.sun.enterprise.tools.common.util.diagnostics.Reporter;
34
35 public class ObjectAnalyzer
36 {
37     public static String JavaDoc getMethods(String JavaDoc className)
38     {
39         try
40         {
41             Class JavaDoc clazz = Class.forName(className);
42             return getMethods(clazz, false);
43         }
44         catch(Exception JavaDoc e)
45         {
46             return "Error loading class: " + e.getMessage();//NOI18N
47
}
48     }
49
50     ////////////////////////////////////////////////////////////////////////////
51

52     public static String JavaDoc getMethods(Object JavaDoc obj)
53     {
54         return getMethods(obj, false);
55     }
56
57     ////////////////////////////////////////////////////////////////////////////
58

59     public static String JavaDoc getMethods(Object JavaDoc obj, boolean settersOnly)
60     {
61         try
62         {
63             Class JavaDoc clazz = safeGetClass(obj);
64             return getMethods(clazz, settersOnly);
65         }
66         catch(Exception JavaDoc e)
67         {
68             return e.getMessage();
69         }
70     }
71
72     ////////////////////////////////////////////////////////////////////////////
73

74     public static String JavaDoc getMethods(Class JavaDoc clazz, boolean settersOnly)
75     {
76         String JavaDoc s = new String JavaDoc();
77
78         Method[] methods = clazz.getMethods();
79
80         for(int i = 0; i < methods.length; i++)
81         {
82             Method m = methods[i];
83             boolean isSetter = m.getName().startsWith("set");//NOI18N
84

85             if(settersOnly && isSetter == false)
86                 continue;
87             
88             s = s + m.toString() + '\n';
89         }
90         return s;
91     }
92
93     ////////////////////////////////////////////////////////////////////////////
94

95     public static String JavaDoc getSetters(Object JavaDoc obj)
96     {
97         return getMethods(obj, true);
98     }
99
100     ////////////////////////////////////////////////////////////////////////////
101

102     public static String JavaDoc getSetters(Class JavaDoc clazz)
103     {
104         return getMethods(clazz, true);
105     }
106
107     ////////////////////////////////////////////////////////////////////////////
108

109     public static String JavaDoc toString(Object JavaDoc obj)
110     {
111         return toString(obj, false);
112     }
113
114     ////////////////////////////////////////////////////////////////////////////
115

116     public static String JavaDoc toStringWithSuper(Object JavaDoc obj)
117     {
118         return toString(obj, true);
119     }
120
121     ////////////////////////////////////////////////////////////////////////////
122

123     public static boolean equals(Object JavaDoc a, Object JavaDoc b)
124     {
125         Class JavaDoc cl = a.getClass();
126
127         if (!cl.equals(b.getClass()))
128             return false;
129         
130         Field[] fields = cl.getDeclaredFields();
131         setAccessible(fields);
132         
133         for (int i = 0; i < fields.length; i++)
134         {
135             Field f = fields[i];
136             try
137             {
138                 if (!f.get(a).equals(f.get(b)))
139                     return false;
140             }
141             catch(IllegalAccessException JavaDoc e)
142             {
143                 return false;
144             }
145         }
146         
147         return true;
148     }
149
150     ////////////////////////////////////////////////////////////////////////////
151

152     public static void useShortClassNames()
153     {
154         useShortClassNames_ = true;
155     }
156
157     ////////////////////////////////////////////////////////////////////////////
158

159     public static void useLongClassNames()
160     {
161         useShortClassNames_ = false;
162     }
163
164     ////////////////////////////////////////////////////////////////////////////
165

166     private static String JavaDoc toString(Object JavaDoc obj, boolean doSuperClasses)
167     {
168         try
169         {
170             return getFieldInfo(obj, doSuperClasses).toString();
171         }
172         catch(ObjectAnalyzerException e)
173         {
174             return e.getMessage();
175         }
176     }
177     
178     ////////////////////////////////////////////////////////////////////////////
179

180     private static Class JavaDoc safeGetClass(Object JavaDoc obj) throws ObjectAnalyzerException
181     {
182         if(obj == null)
183             throw new ObjectAnalyzerException(fatal + "null Object parameter");//NOI18N
184

185         if(! (obj instanceof Object JavaDoc))
186             throw new ObjectAnalyzerException(fatal + "Object parameter is not really a java.lang.Object");//NOI18N
187

188         Class JavaDoc cl = obj.getClass();
189
190         if(cl == null)
191             throw new ObjectAnalyzerException(fatal + "getClass() on parameter Object returned null");//NOI18N
192

193         return cl;
194     }
195     
196     ////////////////////////////////////////////////////////////////////////////
197

198     private static Class JavaDoc safeGetSuperclass(Class JavaDoc cl) throws ObjectAnalyzerException
199     {
200         Class JavaDoc sc = cl.getSuperclass();
201
202         if(sc == null)
203             throw new ObjectAnalyzerException("getSuperclass() on parameter Object returned null");//NOI18N
204

205         return sc;
206     }
207     
208     ////////////////////////////////////////////////////////////////////////////
209

210     private static FieldInfoVector getFieldInfo(Object JavaDoc obj, boolean doSuperClasses) throws ObjectAnalyzerException
211     {
212         FieldInfoVector fiv = new FieldInfoVector();
213         Class JavaDoc cl = safeGetClass(obj);
214
215         if(doSuperClasses == false)
216         {
217             getFieldInfo(cl, obj, fiv);
218             return fiv;
219         }
220
221         for(Class JavaDoc theClass = cl; theClass != null && !theClass.equals(Object JavaDoc.class); theClass = safeGetSuperclass(theClass))
222             getFieldInfo(theClass, obj, fiv);
223
224         return fiv;
225     }
226     
227     
228     ////////////////////////////////////////////////////////////////////////////
229

230     private static void getFieldInfo(Class JavaDoc cl, Object JavaDoc obj, FieldInfoVector fiv) throws ObjectAnalyzerException
231     {
232         Field[] fields = null;
233
234         try
235         {
236             fields = cl.getDeclaredFields();
237         }
238         catch(SecurityException JavaDoc e)
239         {
240             throw new ObjectAnalyzerException("got a SecurityException when calling getDeclaredFields() on " + cl.getName());//NOI18N
241
}
242
243         if(fields == null)
244             throw new ObjectAnalyzerException("calling getDeclaredFields() on " + cl.getName() + " returned null");//NOI18N
245

246         setAccessible(fields);
247
248         for(int i = 0; i < fields.length; i++)
249         {
250             Field f = fields[i];
251             String JavaDoc sval;
252             String JavaDoc modifiers = Modifier.toString(f.getModifiers());
253             String JavaDoc className = cl.getName();
254
255             if(useShortClassNames_)
256                 className = StringUtils.toShortClassName(className);
257
258             if(modifiers.length() <= 0)
259                 modifiers = "(package)";//NOI18N
260

261             try
262             {
263                 Object JavaDoc val = f.get(obj);
264                 
265                 if(val == null)
266                     sval = "<null>";//NOI18N
267
else
268                     sval = val.toString();
269             }
270             catch (IllegalAccessException JavaDoc e)
271             {
272                 sval = "<IllegalAccessException>";//NOI18N
273
}
274             
275             fiv.addElement(new FieldInfo(className, f, sval, modifiers));
276         }
277     }
278     
279     ////////////////////////////////////////////////////////////////////////////
280

281     private static void setAccessible(Field[] fields)
282     {
283         if(setAccessibleMethod == null)
284             return; // Must be pre JDK 1.2.x
285

286         try
287         {
288             Boolean JavaDoc b = new Boolean JavaDoc(true);
289             setAccessibleMethod.invoke(null, new Object JavaDoc[] { fields, b } );
290         }
291         catch(Exception JavaDoc e)
292         {
293             Reporter.warn("Got an exception invoking setAccessible: " + e);//NOI18N
294
}
295     }
296
297     ////////////////////////////////////////////////////////////////////////////
298

299     private static void setupSetAccessibleMethod()
300     {
301         // whoa! what's this reflection crap doing here?
302
// AccessibleObject is a JDK 1.2 class that lets you peek at
303
// private variable values. Since we need to support JDK 1.1
304
// for the VCafe plug-in -- it is now called via 100% reflection
305
// techniques...
306

307         setAccessibleMethod = null;
308
309         Class JavaDoc AO;
310
311         try
312         {
313             AO = Class.forName("java.lang.reflect.AccessibleObject");//NOI18N
314
}
315         catch(ClassNotFoundException JavaDoc e)
316         {
317             Reporter.info("Can't find java.lang.reflect.AccessibleObject -- thus I can't show any private or protected variable values. This must be pre JDK 1.2.x");//NOI18N
318
return;
319         }
320
321         Method[] methods = AO.getDeclaredMethods();
322
323         for(int i = 0; i < methods.length; i++)
324         {
325             Method m = methods[i];
326
327             if(m.getName().equals("setAccessible") && m.getParameterTypes().length == 2)//NOI18N
328
{
329                 Reporter.verbose("Found setAccessible: " + m);//NOI18N
330
setAccessibleMethod = m;
331                 break;
332             }
333         }
334     }
335     
336     
337     ////////////////////////////////////////////////////////////////////////////
338

339     private static final String JavaDoc fatal = "Fatal Error in ObjectAnalyzer.toString(): ";//NOI18N
340
private static boolean useShortClassNames_ = true;
341     private static Method setAccessibleMethod;
342
343     static
344     {
345         setupSetAccessibleMethod();
346     }
347     
348     ////////////////////////////////////////////////////////////////////////////
349

350     public static void main(String JavaDoc[] args)
351     {
352         String JavaDoc s = new String JavaDoc("Hello!");//NOI18N
353

354         System.out.println("Regular: \n" + toString(s) + "\n\n");//NOI18N
355
System.out.println("Super: \n" + toStringWithSuper(s) + "\n\n");//NOI18N
356
}
357       
358 }
359
360 ////////////////////////////////////////////////////////////////////////////
361
////////////////////////////////////////////////////////////////////////////
362

363 class ObjectAnalyzerException extends Exception JavaDoc
364 {
365     ObjectAnalyzerException(String JavaDoc s)
366     {
367         super(s);
368     }
369
370 }
371     
372 ////////////////////////////////////////////////////////////////////////////
373
////////////////////////////////////////////////////////////////////////////
374

375 class FieldInfo
376 {
377     Field field;
378     String JavaDoc value;
379     //Class clazz;
380
String JavaDoc className;
381     String JavaDoc modifiers;
382
383     FieldInfo(String JavaDoc c, Field f, String JavaDoc v, String JavaDoc m)
384     {
385         className = c;
386         field = f;
387         value = v;
388         modifiers = m;
389     }
390 }
391     
392 ////////////////////////////////////////////////////////////////////////////
393
////////////////////////////////////////////////////////////////////////////
394

395 class FieldInfoVector // { extends Vector
396
{
397     Vector JavaDoc v = null;
398     
399     FieldInfoVector()
400     {
401         v = new Vector JavaDoc();
402     }
403     
404     ////////////////////////////////////////////////////////////////////////////
405

406     public void addElement(Object JavaDoc o) {
407         v.addElement(o);
408     }
409     
410     ////////////////////////////////////////////////////////////////////////////
411

412     public String JavaDoc toString()
413     {
414         int veclen = v.size();
415         StringBuffer JavaDoc s = new StringBuffer JavaDoc();
416
417         setLongestNames();
418
419         //s.append("classNameLength: " + classNameLength + "fieldNameLength: " + fieldNameLength + "modifiersLength: " + modifiersLength + "\n\n");//NOI18N
420

421         s.append(StringUtils.padRight("Class", classNameLength));//NOI18N
422
s.append(StringUtils.padRight("Modifiers", modifiersLength));//NOI18N
423
s.append(StringUtils.padRight("Field", fieldNameLength));//NOI18N
424
s.append("Value");//NOI18N
425
s.append("\n\n");//NOI18N
426

427         for(int i = 0; i < veclen; i++)
428         {
429             FieldInfo fi = fetch(i);
430     
431             s.append(StringUtils.padRight(fi.className, classNameLength));
432             s.append(StringUtils.padRight(fi.modifiers, modifiersLength));
433             s.append(StringUtils.padRight(fi.field.getName(), fieldNameLength));
434             s.append(fi.value);
435             s.append('\n');
436         }
437
438         return s.toString();
439     }
440
441     ////////////////////////////////////////////////////////////////////////////
442

443     private FieldInfo fetch(int i)
444     {
445         return (FieldInfo)v.elementAt(i);
446     }
447     
448     ////////////////////////////////////////////////////////////////////////////
449

450     private void setLongestNames()
451     {
452         int veclen = v.size();
453
454         classNameLength = 5;
455         fieldNameLength = 5;
456         modifiersLength = 5;
457
458         for(int i = 0; i < veclen; i++)
459         {
460             FieldInfo fi = fetch(i);
461
462             int clen = fi.className.length();
463             int flen = fi.field.getName().length();
464             int mlen = fi.modifiers.length();
465             if(clen > classNameLength) classNameLength = clen;
466             if(flen > fieldNameLength) fieldNameLength = flen;
467             if(mlen > modifiersLength) modifiersLength = mlen;
468         }
469
470         classNameLength += 2;
471         fieldNameLength += 2;
472         modifiersLength += 2;
473     }
474
475     ////////////////////////////////////////////////////////////////////////////
476

477     private int classNameLength = 0;
478     private int fieldNameLength = 0;
479     private int modifiersLength = 0;
480
481 }
482
483 ////////////////////////////////////////////////////////////////////////////
484
////////////////////////////////////////////////////////////////////////////
485

486 ////////////////////////////////////////////////////////////////////////////
487
// ******** Holding Area for Testing Crap ....... *********
488
////////////////////////////////////////////////////////////////////////////
489

490 /*
491 class foo extends gooxxxxxxxxxx
492 {
493     foo() { f_1 = 5; }
494     int f_1, f_2 = 3;
495 }
496
497 class gooxxxxxxxxxx extends hoo
498 {
499     gooxxxxxxxxxx() { g_1 = 7; }
500     private int g_1, g_2 = 99;
501 }
502 class hoo
503 {
504     hoo() { h_1e43423214dssdfff = 27; }
505     int h_1e43423214dssdfff;
506 }
507
508   
509     
510     
511     ////////////////////////////////////////////////////////////////////////////
512
513     public static void main(String[] args)
514     {
515         foo e = new foo();
516
517         System.out.println("Regular: \n" + toString(e) + "\n\n"); //NOI18N
518         System.out.println("Super: \n" + toStringWithSuper(e) + "\n\n"); //NOI18N
519     }
520       
521     private static void debug(String s)
522     {
523         if(!debug_)
524             return;
525     
526         System.out.println("&&&&& ObjectAnalyzer <<" + s + ">>"); //NOI18N
527     }
528     
529     ////////////////////////////////////////////////////////////////////////////
530
531     private static final boolean debug_ = true;
532 */

533
534
535
Popular Tags