KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > config > backup > 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.config.backup.util;
30
31 import java.lang.reflect.*;
32 import java.util.Vector JavaDoc;
33
34 public class ObjectAnalyzer
35 {
36     /**
37      * @param className
38      * @return */

39     public static String JavaDoc getMethods(String JavaDoc className)
40     {
41         try
42         {
43             Class JavaDoc clazz = Class.forName(className);
44             return getMethods(clazz, false);
45         }
46         catch(Exception JavaDoc e)
47         {
48             return "Error loading class: " + e.getMessage();//NOI18N
49
}
50     }
51
52     ////////////////////////////////////////////////////////////////////////////
53

54     /**
55      * @param obj
56      * @return */

57     public static String JavaDoc getMethods(Object JavaDoc obj)
58     {
59         return getMethods(obj, false);
60     }
61
62     ////////////////////////////////////////////////////////////////////////////
63

64     /**
65      * @param obj
66      * @param settersOnly
67      * @return */

68     public static String JavaDoc getMethods(Object JavaDoc obj, boolean settersOnly)
69     {
70         try
71         {
72             Class JavaDoc clazz = safeGetClass(obj);
73             return getMethods(clazz, settersOnly);
74         }
75         catch(Exception JavaDoc e)
76         {
77             return e.getMessage();
78         }
79     }
80
81     ////////////////////////////////////////////////////////////////////////////
82

83     /**
84      * @param clazz
85      * @param settersOnly
86      * @return */

87     public static String JavaDoc getMethods(Class JavaDoc clazz, boolean settersOnly)
88     {
89         String JavaDoc s = new String JavaDoc();
90
91         Method[] methods = clazz.getMethods();
92
93         for(int i = 0; i < methods.length; i++)
94         {
95             Method m = methods[i];
96             boolean isSetter = m.getName().startsWith("set");//NOI18N
97

98             if(settersOnly && isSetter == false)
99                 continue;
100             
101             s = s + m.toString() + '\n';
102         }
103         return s;
104     }
105
106     ////////////////////////////////////////////////////////////////////////////
107

108     /**
109      * @param obj
110      * @return */

111     public static String JavaDoc getSetters(Object JavaDoc obj)
112     {
113         return getMethods(obj, true);
114     }
115
116     ////////////////////////////////////////////////////////////////////////////
117

118     /**
119      * @param clazz
120      * @return */

121     public static String JavaDoc getSetters(Class JavaDoc clazz)
122     {
123         return getMethods(clazz, true);
124     }
125
126     ////////////////////////////////////////////////////////////////////////////
127

128     /**
129      * @param obj
130      * @return */

131     public static String JavaDoc toString(Object JavaDoc obj)
132     {
133         return toString(obj, false);
134     }
135
136     ////////////////////////////////////////////////////////////////////////////
137

138     /**
139      * @param obj
140      * @return */

141     public static String JavaDoc toStringWithSuper(Object JavaDoc obj)
142     {
143         return toString(obj, true);
144     }
145
146     ////////////////////////////////////////////////////////////////////////////
147

148     /**
149      * @param a
150      * @param b
151      * @return */

152     public static boolean equals(Object JavaDoc a, Object JavaDoc b)
153     {
154         Class JavaDoc cl = a.getClass();
155
156         if (!cl.equals(b.getClass()))
157             return false;
158         
159         Field[] fields = cl.getDeclaredFields();
160         setAccessible(fields);
161         
162         for (int i = 0; i < fields.length; i++)
163         {
164             Field f = fields[i];
165             try
166             {
167                 if (!f.get(a).equals(f.get(b)))
168                     return false;
169             }
170             catch(IllegalAccessException JavaDoc e)
171             {
172                 return false;
173             }
174         }
175         
176         return true;
177     }
178
179     ////////////////////////////////////////////////////////////////////////////
180

181     public static void useShortClassNames()
182     {
183         useShortClassNames_ = true;
184     }
185
186     ////////////////////////////////////////////////////////////////////////////
187

188     public static void useLongClassNames()
189     {
190         useShortClassNames_ = false;
191     }
192
193     ////////////////////////////////////////////////////////////////////////////
194

195     private static String JavaDoc toString(Object JavaDoc obj, boolean doSuperClasses)
196     {
197         try
198         {
199             return getFieldInfo(obj, doSuperClasses).toString();
200         }
201         catch(ObjectAnalyzerException e)
202         {
203             return e.getMessage();
204         }
205     }
206     
207     ////////////////////////////////////////////////////////////////////////////
208

209     private static Class JavaDoc safeGetClass(Object JavaDoc obj) throws ObjectAnalyzerException
210     {
211         if(obj == null)
212             throw new ObjectAnalyzerException(fatal + "null Object parameter");//NOI18N
213

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

217         Class JavaDoc cl = obj.getClass();
218
219         if(cl == null)
220             throw new ObjectAnalyzerException(fatal + "getClass() on parameter Object returned null");//NOI18N
221

222         return cl;
223     }
224     
225     ////////////////////////////////////////////////////////////////////////////
226

227     private static Class JavaDoc safeGetSuperclass(Class JavaDoc cl) throws ObjectAnalyzerException
228     {
229         Class JavaDoc sc = cl.getSuperclass();
230
231         if(sc == null)
232             throw new ObjectAnalyzerException("getSuperclass() on parameter Object returned null");//NOI18N
233

234         return sc;
235     }
236     
237     ////////////////////////////////////////////////////////////////////////////
238

239     private static FieldInfoVector getFieldInfo(Object JavaDoc obj, boolean doSuperClasses) throws ObjectAnalyzerException
240     {
241         FieldInfoVector fiv = new FieldInfoVector();
242         Class JavaDoc cl = safeGetClass(obj);
243
244         if(doSuperClasses == false)
245         {
246             getFieldInfo(cl, obj, fiv);
247             return fiv;
248         }
249
250         for(Class JavaDoc theClass = cl; theClass != null && !theClass.equals(Object JavaDoc.class); theClass = safeGetSuperclass(theClass))
251             getFieldInfo(theClass, obj, fiv);
252
253         return fiv;
254     }
255     
256     
257     ////////////////////////////////////////////////////////////////////////////
258

259     private static void getFieldInfo(Class JavaDoc cl, Object JavaDoc obj, FieldInfoVector fiv) throws ObjectAnalyzerException
260     {
261         Field[] fields = null;
262
263         try
264         {
265             fields = cl.getDeclaredFields();
266         }
267         catch(SecurityException JavaDoc e)
268         {
269             throw new ObjectAnalyzerException("got a SecurityException when calling getDeclaredFields() on " + cl.getName());//NOI18N
270
}
271
272         if(fields == null)
273             throw new ObjectAnalyzerException("calling getDeclaredFields() on " + cl.getName() + " returned null");//NOI18N
274

275         setAccessible(fields);
276
277         for(int i = 0; i < fields.length; i++)
278         {
279             Field f = fields[i];
280             String JavaDoc sval;
281             String JavaDoc modifiers = Modifier.toString(f.getModifiers());
282             String JavaDoc className = cl.getName();
283
284             if(useShortClassNames_)
285                 className = StringUtils.toShortClassName(className);
286
287             if(modifiers.length() <= 0)
288                 modifiers = "(package)";//NOI18N
289

290             try
291             {
292                 Object JavaDoc val = f.get(obj);
293                 
294                 if(val == null)
295                     sval = "<null>";//NOI18N
296
else
297                     sval = val.toString();
298             }
299             catch (IllegalAccessException JavaDoc e)
300             {
301                 sval = "<IllegalAccessException>";//NOI18N
302
}
303             
304             fiv.addElement(new FieldInfo(className, f, sval, modifiers));
305         }
306     }
307     
308     ////////////////////////////////////////////////////////////////////////////
309

310     private static void setAccessible(Field[] fields)
311     {
312         if(setAccessibleMethod == null)
313             return; // Must be pre JDK 1.2.x
314

315         try
316         {
317             Boolean JavaDoc b = new Boolean JavaDoc(true);
318             setAccessibleMethod.invoke(null, new Object JavaDoc[] { fields, b } );
319         }
320         catch(Exception JavaDoc e)
321         {
322         }
323     }
324
325     ////////////////////////////////////////////////////////////////////////////
326

327     private static void setupSetAccessibleMethod()
328     {
329         // whoa! what's this reflection crap doing here?
330
// AccessibleObject is a JDK 1.2 class that lets you peek at
331
// private variable values. Since we need to support JDK 1.1
332
// for the VCafe plug-in -- it is now called via 100% reflection
333
// techniques...
334

335         setAccessibleMethod = null;
336
337         Class JavaDoc AO;
338
339         try
340         {
341             AO = Class.forName("java.lang.reflect.AccessibleObject");//NOI18N
342
}
343         catch(ClassNotFoundException JavaDoc e)
344         {
345             return;
346         }
347
348         Method[] methods = AO.getDeclaredMethods();
349
350         for(int i = 0; i < methods.length; i++)
351         {
352             Method m = methods[i];
353
354             if(m.getName().equals("setAccessible") && m.getParameterTypes().length == 2)//NOI18N
355
{
356                 setAccessibleMethod = m;
357                 break;
358             }
359         }
360     }
361     
362     
363     ////////////////////////////////////////////////////////////////////////////
364

365     private static final String JavaDoc fatal = "Fatal Error in ObjectAnalyzer.toString(): ";//NOI18N
366
private static boolean useShortClassNames_ = true;
367     private static Method setAccessibleMethod;
368
369     static
370     {
371         setupSetAccessibleMethod();
372     }
373     
374     ////////////////////////////////////////////////////////////////////////////
375

376     /**
377      * @param args */

378     public static void main(String JavaDoc[] args)
379     {
380         String JavaDoc s = new String JavaDoc("Hello!");//NOI18N
381

382         System.out.println("Regular: \n" + toString(s) + "\n\n");//NOI18N
383
System.out.println("Super: \n" + toStringWithSuper(s) + "\n\n");//NOI18N
384
}
385       
386 }
387
388 ////////////////////////////////////////////////////////////////////////////
389
////////////////////////////////////////////////////////////////////////////
390

391 class ObjectAnalyzerException extends Exception JavaDoc
392 {
393     ObjectAnalyzerException(String JavaDoc s)
394     {
395         super(s);
396     }
397
398 }
399     
400 ////////////////////////////////////////////////////////////////////////////
401
////////////////////////////////////////////////////////////////////////////
402

403 class FieldInfo
404 {
405     Field field;
406     String JavaDoc value;
407     //Class clazz;
408
String JavaDoc className;
409     String JavaDoc modifiers;
410
411     FieldInfo(String JavaDoc c, Field f, String JavaDoc v, String JavaDoc m)
412     {
413         className = c;
414         field = f;
415         value = v;
416         modifiers = m;
417     }
418 }
419     
420 ////////////////////////////////////////////////////////////////////////////
421
////////////////////////////////////////////////////////////////////////////
422

423 class FieldInfoVector // { extends Vector
424
{
425     Vector JavaDoc v = null;
426     
427     FieldInfoVector()
428     {
429         v = new Vector JavaDoc();
430     }
431     
432     ////////////////////////////////////////////////////////////////////////////
433

434     /**
435      * @param o */

436     public void addElement(Object JavaDoc o) {
437         v.addElement(o);
438     }
439     
440     ////////////////////////////////////////////////////////////////////////////
441

442     /**
443      * @return */

444     public String JavaDoc toString()
445     {
446         int veclen = v.size();
447         StringBuffer JavaDoc s = new StringBuffer JavaDoc();
448
449         setLongestNames();
450
451         //s.append("classNameLength: " + classNameLength + "fieldNameLength: " + fieldNameLength + "modifiersLength: " + modifiersLength + "\n\n");//NOI18N
452

453         s.append(StringUtils.padRight("Class", classNameLength));//NOI18N
454
s.append(StringUtils.padRight("Modifiers", modifiersLength));//NOI18N
455
s.append(StringUtils.padRight("Field", fieldNameLength));//NOI18N
456
s.append("Value");//NOI18N
457
s.append("\n\n");//NOI18N
458

459         for(int i = 0; i < veclen; i++)
460         {
461             FieldInfo fi = fetch(i);
462     
463             s.append(StringUtils.padRight(fi.className, classNameLength));
464             s.append(StringUtils.padRight(fi.modifiers, modifiersLength));
465             s.append(StringUtils.padRight(fi.field.getName(), fieldNameLength));
466             s.append(fi.value);
467             s.append('\n');
468         }
469
470         return s.toString();
471     }
472
473     ////////////////////////////////////////////////////////////////////////////
474

475     private FieldInfo fetch(int i)
476     {
477         return (FieldInfo)v.elementAt(i);
478     }
479     
480     ////////////////////////////////////////////////////////////////////////////
481

482     private void setLongestNames()
483     {
484         int veclen = v.size();
485
486         classNameLength = 5;
487         fieldNameLength = 5;
488         modifiersLength = 5;
489
490         for(int i = 0; i < veclen; i++)
491         {
492             FieldInfo fi = fetch(i);
493
494             int clen = fi.className.length();
495             int flen = fi.field.getName().length();
496             int mlen = fi.modifiers.length();
497             if(clen > classNameLength) classNameLength = clen;
498             if(flen > fieldNameLength) fieldNameLength = flen;
499             if(mlen > modifiersLength) modifiersLength = mlen;
500         }
501
502         classNameLength += 2;
503         fieldNameLength += 2;
504         modifiersLength += 2;
505     }
506
507     ////////////////////////////////////////////////////////////////////////////
508

509     private int classNameLength = 0;
510     private int fieldNameLength = 0;
511     private int modifiersLength = 0;
512 }
513
Popular Tags