KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > appserv > management > util > misc > ClassUtil


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  * $Header: /cvs/glassfish/admin-core/mbeanapi/src/java/com/sun/appserv/management/util/misc/ClassUtil.java,v 1.5 2006/03/09 20:30:33 llc Exp $
26  * $Revision: 1.5 $
27  * $Date: 2006/03/09 20:30:33 $
28  */

29
30 package com.sun.appserv.management.util.misc;
31
32 import java.lang.reflect.Array JavaDoc;
33 import java.lang.reflect.Field JavaDoc;
34 import java.lang.reflect.Constructor JavaDoc;
35 import java.lang.reflect.Method JavaDoc;
36 import java.lang.ClassLoader JavaDoc;
37
38 import java.util.Set JavaDoc;
39 import java.util.HashSet JavaDoc;
40
41 /*
42     Used internally.
43  */

44 final class ClassToClassMapping
45 {
46     final Class JavaDoc mSrc;
47     final Class JavaDoc mDest;
48
49         public
50     ClassToClassMapping( Class JavaDoc src, Class JavaDoc dest )
51     {
52         mSrc = src;
53         mDest = dest;
54     }
55 }
56
57
58 /**
59     Provides a variety of useful utilities having to do with classes, types of
60     objects, etc.
61  */

62 public final class ClassUtil
63 {
64         private
65     ClassUtil( )
66     {
67         // disallow instantiation
68
}
69     
70         public static boolean
71     classIsAccessible( String JavaDoc name )
72     {
73         boolean accessible = false;
74         
75         try
76         {
77             accessible = getClassFromName( name ) != null;
78         }
79         catch( ClassNotFoundException JavaDoc e )
80         {
81         }
82         return( accessible );
83     }
84     
85     
86         public static boolean
87     sigsEqual(
88         final Class JavaDoc[] sig1,
89         final Class JavaDoc[] sig2 )
90     {
91         boolean equal = sig1.length == sig2.length;
92         
93         if ( equal )
94         {
95             for( int i = 0; i < sig1.length; ++i )
96             {
97                 if ( sig1[ i ] != sig2[ i ] )
98                 {
99                     equal = false;
100                     break;
101                 }
102             }
103         }
104         
105         return( equal );
106     }
107     /**
108         Test whether an Object is an array
109         
110         @param o object to test
111         @return true if the object is an array, false otherwise.
112      */

113         public static boolean
114     objectIsArray( Object JavaDoc o )
115     {
116         return( classIsArray( o.getClass() ) );
117     }
118     
119     /**
120         Test whether a Class is an array
121         
122         @param theClass class to test
123         @return true if the class is an array, false otherwise.
124      */

125         public static boolean
126     classIsArray( Class JavaDoc theClass )
127     {
128         return( classnameIsArray( theClass.getName() ) );
129     }
130     
131     /**
132         Test whether an Object is an array of primitive types
133         
134         @param o object to test
135         @return true if the object is an array, false otherwise.
136      */

137         public static boolean
138     objectIsPrimitiveArray( Object JavaDoc o )
139     {
140         return( getPrimitiveArrayTypeCode( o.getClass() ) != 0 );
141     }
142     
143     /**
144         Test whether a classname is an array
145         
146         @param classname classname string
147         @return true if the object is an array, false otherwise.
148      */

149         public static boolean
150     classnameIsArray( String JavaDoc classname )
151     {
152         return( classname.startsWith( "[" ) );
153     }
154     
155     /**
156         Strip the package name.
157         
158         @param classname classname string
159         @return the classname, without its package
160      */

161         public static String JavaDoc
162     stripPackageName( String JavaDoc classname )
163     {
164         final int lastDot = classname.lastIndexOf( "." );
165         if ( lastDot < 0 )
166         {
167             return( classname );
168         }
169         
170         return( classname.substring( lastDot + 1, classname.length() ) );
171     }
172     
173     
174     /**
175         Test whether a classname is a primitive array
176         
177         @param classname classname string
178         @return true if the object is a primitive array, false otherwise.
179      */

180         public static boolean
181     classnameIsPrimitiveArray( String JavaDoc classname )
182     {
183         return( getPrimitiveArrayTypeCode( classname ) != 0 );
184     }
185     
186     /**
187         Return the primitive element type code for an array of primitive types.
188         Same as getPrimitiveArrayTypeCode( theClass.getName() )
189         
190         @param theClass the Class object
191         @return the element type code; otherwise (char)0
192      */

193         public static char
194     getPrimitiveArrayTypeCode( Class JavaDoc theClass )
195     {
196         char typeCode = 0;
197         
198         if ( classIsArray( theClass ) )
199         {
200             typeCode = getPrimitiveArrayTypeCode( theClass.getName() );
201         }
202         
203         return( typeCode );
204     }
205     
206     /**
207         Return the primitive element type code for an array of primitive types.
208         
209         @param classname classname string
210         @return the element type code; otherwise (char)0
211      */

212         public static char
213     getPrimitiveArrayTypeCode( String JavaDoc classname )
214     {
215         char typeCode = 0;
216         
217         final int length = classname.length();
218         
219         if ( classnameIsArray( classname ) &&
220                 classname.charAt( length - 2 ) == '[' )
221         {
222             typeCode = classname.charAt( length - 1 );
223             
224             switch( typeCode )
225             {
226                 default: typeCode = 0; break;
227                 
228                 case 'Z':
229                 case 'B':
230                 case 'C':
231                 case 'S':
232                 case 'I':
233                 case 'J':
234                 case 'F':
235                 case 'D':
236                     break;
237             }
238         }
239         
240         return( typeCode );
241     }
242     
243  
244     /**
245         Get the classname for an array element.
246         
247         @param classname classname string
248         @return the classname for the array element
249      */

250         public static String JavaDoc
251     getArrayMemberClassName( String JavaDoc classname )
252     {
253         String JavaDoc result = null;
254         
255         if ( ! classnameIsArray( classname ) )
256         {
257             throw new IllegalArgumentException JavaDoc( "not an array" );
258         }
259         
260         final int classnameLength = classname.length();
261         
262         
263         if ( classnameIsPrimitiveArray( classname ) )
264         {
265             final char lastChar = classname.charAt(classnameLength -1 );
266             
267             switch( lastChar )
268             {
269                 default: throw new RuntimeException JavaDoc( "illegal primitive" );
270                 
271                 // a simple type
272
case 'Z': result = "boolean"; break;
273                 case 'B': result = "byte"; break;
274                 case 'C': result = "char"; break;
275                 case 'S': result = "short"; break;
276                 case 'I': result = "int"; break;
277                 case 'J': result = "long"; break;
278                 case 'F': result = "float"; break;
279                 case 'D': result = "double"; break;
280             }
281         }
282         else
283         {
284             // strip leading "[L" and trailing ";"
285
result = classname.substring( 2, classnameLength - 1 );
286         }
287         
288         return( result );
289     }
290     
291
292     
293          
294     /**
295         Class.forName does not work for primitive types, so we need to do it ourselves here.
296      */

297     final static class ClassNameToClassMapping
298     {
299         String JavaDoc mName;
300         Class JavaDoc mClass;
301
302         ClassNameToClassMapping( String JavaDoc name, Class JavaDoc theClass )
303         {
304             mName = name;
305             mClass = theClass;
306         }
307     }
308     
309     private static final ClassNameToClassMapping [] sPrimitiveNameToObjectClass =
310         new ClassNameToClassMapping []
311         {
312             new ClassNameToClassMapping( "int", int.class ),
313             new ClassNameToClassMapping( "long", long.class ),
314             new ClassNameToClassMapping( "short", short.class ),
315             new ClassNameToClassMapping( "byte", byte.class ),
316             new ClassNameToClassMapping( "boolean", boolean.class ),
317             new ClassNameToClassMapping( "float", float.class ),
318             new ClassNameToClassMapping( "double", double.class ),
319             new ClassNameToClassMapping( "char", char.class ),
320             new ClassNameToClassMapping( "void", void.class ),
321         };
322     
323     
324         public static Class JavaDoc<?>
325     classForName( String JavaDoc name )
326         throws ClassNotFoundException JavaDoc
327     {
328         Class JavaDoc<?> c = null;
329         
330         try
331         {
332             c = Class.forName( name );
333         }
334         catch ( ClassNotFoundException JavaDoc e )
335         {
336             c = Class.forName( name, true, Thread.currentThread().getContextClassLoader() );
337         }
338         catch ( NoClassDefFoundError JavaDoc e )
339         {
340             c = Class.forName( name, true, Thread.currentThread().getContextClassLoader() );
341         }
342         
343         return( c );
344     }
345     
346     /**
347         Get a Class from a classname. Class.forName does not work for primitive types;
348         this methods returns the correct Class for any type.
349         
350         @param classname classname string
351         @return the classname for the array element
352      */

353         public static Class JavaDoc
354     getClassFromName( final String JavaDoc classname )
355         throws ClassNotFoundException JavaDoc
356     {
357         Class JavaDoc theClass = null;
358         
359         if ( classname.startsWith( "[L" ))
360         {
361             // an array
362
theClass = classForName( classname );
363         }
364         else
365         {
366             final int numMappings = Array.getLength( sPrimitiveNameToObjectClass );
367             for( int i = 0; i < numMappings; ++i )
368             {
369                 if ( sPrimitiveNameToObjectClass[ i ].mName.equals( classname ) )
370                 {
371                     theClass = sPrimitiveNameToObjectClass[ i ].mClass;
372                     break;
373                 }
374             }
375             
376             if ( theClass == null )
377             {
378                 theClass = classForName( classname );
379             }
380         }
381         return( theClass );
382     }
383     
384     
385     private static final ClassToClassMapping [] sPrimitiveClassToObjectClass =
386         new ClassToClassMapping []
387          {
388             new ClassToClassMapping( boolean.class, Boolean JavaDoc.class),
389             new ClassToClassMapping( byte.class, Byte JavaDoc.class ),
390             new ClassToClassMapping( char.class, Character JavaDoc.class ),
391             new ClassToClassMapping( short.class, Short JavaDoc.class ),
392             new ClassToClassMapping( int.class, Integer JavaDoc.class ),
393             new ClassToClassMapping( long.class, Long JavaDoc.class ),
394             new ClassToClassMapping( float.class, Float JavaDoc.class ),
395             new ClassToClassMapping( double.class, Double JavaDoc.class ),
396          };
397     /**
398         Map primitive class Classes to Object forms eg int.class to Integer.class
399         
400         @param theClass the class to map
401         @return the corresponding Object class or the original Class if not a primitive.
402      */

403         public static Class JavaDoc
404     PrimitiveClassToObjectClass( final Class JavaDoc theClass )
405     {
406         Class JavaDoc result = theClass;
407         
408         final int numMappings = Array.getLength( sPrimitiveClassToObjectClass );
409         for( int i = 0; i < numMappings; ++i )
410         {
411             final ClassToClassMapping mapping = sPrimitiveClassToObjectClass[ i ];
412             
413             if ( mapping.mSrc == theClass )
414             {
415                 result = mapping.mDest;
416                 break;
417             }
418         }
419             
420         return( result );
421     }
422     
423     /**
424         Map primitive class Classes to Object forms eg int.class to Integer.class
425         
426         @param theClass the class to map
427         @return the corresponding Object class or the original Class if not a primitive.
428      */

429         public static Class JavaDoc
430     ObjectClassToPrimitiveClass( final Class JavaDoc theClass )
431     {
432         Class JavaDoc result = theClass;
433         
434         final int numMappings = Array.getLength( sPrimitiveClassToObjectClass );
435         for( int i = 0; i < numMappings; ++i )
436         {
437             final ClassToClassMapping mapping = sPrimitiveClassToObjectClass[ i ];
438             
439             if ( mapping.mDest == theClass )
440             {
441                 result = mapping.mSrc;
442                 break;
443             }
444         }
445             
446         return( result );
447     }
448     
449     /**
450         Test whether a class is a primitive class.
451         
452         @param theClass the class to test
453         @return true if it's a primitive class, false otherwise.
454      */

455         public static boolean
456     IsPrimitiveClass( final Class JavaDoc theClass )
457     {
458         boolean isSimple = false;
459         
460         final int numMappings = Array.getLength( sPrimitiveClassToObjectClass );
461         for( int i = 0; i < numMappings; ++i )
462         {
463             final ClassToClassMapping mapping = sPrimitiveClassToObjectClass[ i ];
464             
465             if ( mapping.mSrc.equals( theClass ) )
466             {
467                 isSimple = true;
468                 break;
469             }
470         }
471             
472         return( isSimple );
473     }
474     
475     
476     /**
477         Convert a primitive class letter to its corresponding class name.
478         
479         @param primitive the primitive character code
480         @return the corresponding classname
481      */

482         public static String JavaDoc
483     PrimitiveLetterToClassName( final char primitive)
484     {
485         String JavaDoc result = "" + primitive;
486         
487         // see JavaDoc on Class.getName()
488
switch( primitive )
489         {
490             case 'B': result = "byte"; break;
491             case 'C': result = "char"; break;
492             case 'D': result = "double"; break;
493             case 'F': result = "float"; break;
494             case 'I': result = "int"; break;
495             case 'J': result = "long"; break;
496             case 'S': result = "short"; break;
497             case 'Z': result = "boolean";break;
498         }
499         
500         return( result );
501     }
502     
503
504     /**
505         Return the corresponding classes for each element in an Object[]
506         
507         If an element is null, then its corresponding Class will also be null.
508         
509         @param args an array of objects.
510         @return an array of classes
511      */

512         public static String JavaDoc []
513     getTypes( final Object JavaDoc [] args )
514     {
515         if ( args == null )
516             return( null );
517             
518         final int numArgs = Array.getLength( args );
519         
520         final String JavaDoc [] types = new String JavaDoc [ numArgs ];
521         
522         for( int i = 0; i < numArgs; ++i )
523         {
524             if ( args[ i ] == null )
525             {
526                 types[ i ] = null;
527             }
528             else
529             {
530                 types[ i ] = args[ i ].getClass().getName();
531             }
532         }
533         
534         return( types );
535     }
536     
537     /**
538         Return the corresponding classes for each classname.
539         
540         If an element is null, then its corresponding Class will also be null.
541         
542         @param classnames an array of classnames.
543         @return an array of classes
544      */

545         public static Class JavaDoc[]
546     signatureFromClassnames( String JavaDoc[] classnames )
547         throws ClassNotFoundException JavaDoc
548     {
549         if ( classnames == null )
550         {
551             return( null );
552         }
553         
554         final Class JavaDoc[] signature = new Class JavaDoc[ classnames.length ];
555         
556         for ( int i = 0; i < signature.length; ++i )
557         {
558             signature[ i ] = getClassFromName( classnames[ i ] );
559         }
560         
561         return( signature );
562     }
563     
564         
565     /**
566         Return the corresponding classes for each classname.
567         
568         If an element is null, then its corresponding Class will also be null.
569         
570         @param classes an array of classnames.
571         @return an array of classes
572      */

573         public static String JavaDoc[]
574     classnamesFromSignature( Class JavaDoc[] classes )
575     {
576         final String JavaDoc[] classnames = new String JavaDoc[ classes.length ];
577         
578         for ( int i = 0; i < classnames.length; ++i )
579         {
580             classnames[ i ] = classes[ i ].getName();
581         }
582         
583         return( classnames );
584     }
585
586
587
588     /**
589         Get a "friendly" classname for a Class.
590         <p>
591         Calls getFriendlyClassname( theClass.getName() )
592         
593         @param theClass the class for which the name should be gotten
594         @return the "friendly" name
595      */

596         public static String JavaDoc
597     getFriendlyClassname( Class JavaDoc theClass )
598     {
599         return( getFriendlyClassname( theClass.getName() ) );
600     }
601     
602     /**
603         Convert a Java class name string into a more user friendly string. Examples:
604         <p>
605         java.lang.String => String
606         java.lang.<type> => <type>;
607         [i => int[]
608         [Lfoo.bar.ClassName; => foo.bar.ClassName[]
609         <p>
610         The names returned correspond exactly to what a Java programmer would write, rather
611         than the internal JVM representation.
612         
613         @param type
614         @return a friendlier string representing the type
615      */

616     final static String JavaDoc javaLang = "java.lang.";
617         public static String JavaDoc
618     getFriendlyClassname( String JavaDoc type )
619     {
620         String JavaDoc result = type;
621         
622         if ( type.startsWith( "[" ) )
623         {
624             // count how deep the array is
625
int depth = 0;
626             while ( type.charAt( depth ) == (int)'[' )
627             {
628                 ++depth;
629             }
630             
631             // strip all the '[' characters
632
result = type.substring( depth, type.length() );
633             
634             if ( result.startsWith( "L" ) && result.endsWith( ";" ) )
635             {
636                 result = result.substring( 1, result.length() - 1 );
637             }
638             else if ( result.length() == 1 )
639             {
640                 // a simple type
641
switch( result.charAt( 0 ) )
642                 {
643                     case 'Z': result = "boolean"; break;
644                     case 'B': result = "byte"; break;
645                     case 'C': result = "char"; break;
646                     case 'S': result = "short"; break;
647                     case 'I': result = "int"; break;
648                     case 'J': result = "long"; break;
649                     case 'F': result = "float"; break;
650                     case 'D': result = "double"; break;
651                 }
652             }
653             
654             for( int i = 0; i < depth; ++i )
655             {
656                 result = result + "[]";
657             }
658         }
659         
660         if ( result.startsWith( javaLang ) )
661         {
662             result = result.substring( javaLang.length(), result.length() );
663         }
664         
665         return( result );
666     }
667     
668             
669     /*
670      */

671         public static int
672     getArrayDimensions( final Class JavaDoc theClass )
673     {
674         final String JavaDoc classname = theClass.getName();
675         
676         int dim = 0;
677         while ( classname.charAt( dim ) == '[' )
678         {
679             ++dim;
680         }
681         
682         return( dim );
683     }
684     
685     /*
686      */

687         public static Class JavaDoc
688     getArrayElementClass( final Class JavaDoc arrayClass )
689     {
690         final String JavaDoc arrayClassName = arrayClass.getName();
691             
692         if ( ! classnameIsArray( arrayClassName ) )
693         {
694             throw new IllegalArgumentException JavaDoc( "not an array" );
695         }
696         
697         String JavaDoc name = arrayClassName;
698         
699         // strip leading "["
700
name = name.substring( 1, name.length() );
701         
702         if ( ! name.startsWith( "[" ) )
703         {
704             // element is not an array
705

706             if ( name.startsWith( "L" ) )
707             {
708                 // an Object class; strip leading "L" and trailing ";"
709
name = name.substring( 1, name.length() - 1);
710             }
711             else if ( name.length() == 1 )
712             {
713                 // may be a primitive type
714
name = PrimitiveLetterToClassName( name.charAt( 0 ) );
715             }
716         }
717         else
718         {
719             // element is an array; return it
720
}
721         
722         Class JavaDoc theClass = null;
723         try
724         {
725             theClass = getClassFromName( name );
726         }
727         catch( ClassNotFoundException JavaDoc e )
728         {
729             assert( false );
730         }
731         
732         return( theClass );
733     }
734     
735         public static Class JavaDoc
736     getInnerArrayElementClass( final Class JavaDoc arrayClass )
737         throws ClassNotFoundException JavaDoc
738     {
739         Class JavaDoc elementClass = arrayClass;
740         
741         do
742         {
743             elementClass = getArrayElementClass( elementClass );
744         }
745         while ( classIsArray( elementClass ) );
746         
747         return( elementClass );
748     }
749     
750     
751
752
753         private static Object JavaDoc
754     InstantiateObject( final String JavaDoc theString )
755         throws Exception JavaDoc
756     {
757         Object JavaDoc result = null;
758         
759         try
760         {
761             result = InstantiateNumber( theString );
762         }
763         catch( NumberFormatException JavaDoc e )
764         {
765             result = theString;
766         }
767         
768         return( result );
769     }
770     
771     /**
772         Return true if caller signature is compatible with callee.
773         
774         @param callee the signature of the method to be called
775         @param argsSignature the signature of the argument list
776      */

777         public static boolean
778     signaturesAreCompatible( final Class JavaDoc<?> [] callee, final Class JavaDoc<?> [] argsSignature )
779     {
780         boolean compatible = false;
781         
782         if ( callee.length == argsSignature.length )
783         {
784             compatible = true;
785             
786             for( int i = 0; i < callee.length; ++i )
787             {
788                 if ( ! callee[ i ].isAssignableFrom( argsSignature[ i ] ) )
789                 {
790                     compatible = false;
791                     break;
792                 }
793             }
794         }
795     
796         return( compatible );
797     }
798     
799     /**
800         Find all methods that match the name.
801      */

802         public static final Method JavaDoc
803     findMethod(
804         final Class JavaDoc theClass,
805         final String JavaDoc methodName,
806         final Class JavaDoc[] sig )
807     {
808         Method JavaDoc m = null;
809         try
810         {
811             m = theClass.getMethod( methodName, sig );
812         }
813         catch( NoSuchMethodException JavaDoc e )
814         {
815             // ok, doesn't exist
816
}
817         
818         return( m );
819     }
820     
821     /**
822         Find all methods that match the name.
823      */

824         public static final Set JavaDoc<Method JavaDoc>
825     findMethods(
826         final Method JavaDoc[] candidates,
827         final String JavaDoc methodName )
828     {
829         final Set JavaDoc<Method JavaDoc> s = new HashSet JavaDoc<Method JavaDoc>();
830         
831         for( int methodIdx = 0; methodIdx < candidates.length; ++methodIdx )
832         {
833             final Method JavaDoc method = candidates[ methodIdx ];
834             if ( method.getName().equals( methodName ) )
835             {
836                 s.add( method );
837             }
838         }
839         
840         return( s );
841     }
842     
843     
844     /**
845         Create a new object of the specified class using a constructor
846         that accepts the specified arguments.
847         
848         @param theClass the Class of the desired Object
849         @param args the argument list for the constructor
850      */

851         public static Object JavaDoc
852     InstantiateObject( final Class JavaDoc theClass, final Object JavaDoc [] args )
853         throws Exception JavaDoc
854     {
855         final Class JavaDoc [] signature = new Class JavaDoc [ args.length ];
856         
857         for( int i = 0; i < signature.length; ++i )
858         {
859             signature[ i ] = args[ i ].getClass();
860         }
861         
862         Constructor JavaDoc constructor = null;
863         try
864         {
865             // this will fail if a constructor takes an interface;
866
// the code below will then find a compatible constructor
867
constructor = theClass.getConstructor( signature );
868         }
869         catch( NoSuchMethodException JavaDoc e )
870         {
871             final Constructor JavaDoc [] constructors = theClass.getConstructors();
872             
873             int numMatches = 0;
874             for( int i = 0; i < constructors.length; ++i )
875             {
876                 final Constructor JavaDoc tempConstructor = constructors[ i ];
877                 
878                 final Class JavaDoc [] tempSignature = tempConstructor.getParameterTypes();
879                 
880                 if ( signaturesAreCompatible( tempSignature, signature ) )
881                 {
882                     ++numMatches;
883                     constructor = tempConstructor;
884                     // keep going; there could be more than one valid match
885
}
886             }
887             
888             // to succeed, there must be exactly one match
889
if ( numMatches != 1 )
890             {
891                 throw e;
892             }
893         }
894         
895         Object JavaDoc result = null;
896         try
897         {
898             result = constructor.newInstance( args );
899         }
900         catch( java.lang.reflect.InvocationTargetException JavaDoc e )
901         {
902             // InvocationTargetException wraps the real cause
903
final Throwable JavaDoc cause = e.getCause();
904             
905             if ( cause instanceof Exception JavaDoc )
906             {
907                 throw (Exception JavaDoc)cause;
908             }
909             else
910             {
911                 // shouldn't happen, so we'll just rethrow it
912
throw e;
913             }
914         }
915         
916         return( result );
917     }
918     
919     
920     /**
921         Create a new object of the specified class using a String constructor.
922         
923         @param theClass the Class of the desired Object
924         @param theString the string for a String constructor
925         @return the resulting Object
926      */

927         public static Object JavaDoc
928     InstantiateObject( final Class JavaDoc theClass, final String JavaDoc theString )
929         throws Exception JavaDoc
930     {
931         final Class JavaDoc [] signature = new Class JavaDoc [] { String JavaDoc.class };
932         final Constructor JavaDoc constructor = theClass.getConstructor( signature );
933         
934         Object JavaDoc result = null;
935         try
936         {
937             result = constructor.newInstance( new Object JavaDoc[] { theString } );
938         }
939         catch( java.lang.reflect.InvocationTargetException JavaDoc e )
940         {
941             // InvocationTargetException wraps the real cause
942
Throwable JavaDoc cause = e.getCause();
943             
944             if ( cause instanceof Exception JavaDoc )
945             {
946                 throw (Exception JavaDoc)cause;
947             }
948             else
949             {
950                 // shouldn't happen, so we'll just rethrow it
951
throw e;
952             }
953         }
954         
955         return( result );
956     }
957     
958     /**
959         Create a new number based on a String.
960         <p>
961         Don't get fancy here, simple precedence:
962             Integer, Long if no decimal point, use Long if won't fit in an Integer
963             Double if decimal point (for maximum precision)
964         
965         @param theString String representation of the number
966         @return the resulting Object
967      */

968         private static Object JavaDoc
969     InstantiateNumber( final String JavaDoc theString )
970         throws Exception JavaDoc
971     {
972         Object JavaDoc result = null;
973         
974         if ( theString.indexOf( '.' ) >= 0 )
975         {
976             result = InstantiateObject( Double JavaDoc.class, theString );
977         }
978         else
979         {
980             try
981             {
982                 result = InstantiateObject( Integer JavaDoc.class, theString );
983             }
984             catch( NumberFormatException JavaDoc e )
985             {
986                 // perhaps it wouldn't fit; try it as a long
987
result = InstantiateObject( Long JavaDoc.class, theString );
988             }
989         }
990         return( result );
991     }
992
993     
994     /**
995         Given a Class and a String, create a new instance with a constructor that accept
996         a String. Primitive types are instantiated as their equivalent Object forms.
997         
998         @param theClass the class from which an instance should be instantiated
999         @param theString the string to be supplied to the constructor
1000        @return the resulting Object
1001     */

1002        public static Object JavaDoc
1003    InstantiateFromString( final Class JavaDoc theClass, final String JavaDoc theString )
1004        throws Exception JavaDoc
1005    {
1006        Object JavaDoc result = null;
1007        
1008        // char and Character do not have a String constructor, so we must special-case it
1009
if ( theClass == Object JavaDoc.class )
1010        {
1011            // special case, apply rules to create an object
1012
result = InstantiateObject( theString );
1013        }
1014        else if ( theClass == Number JavaDoc.class )
1015        {
1016            // special case, apply rules to create a number
1017
result = InstantiateNumber( theString );
1018        }
1019        else if ( theClass == Character JavaDoc.class || theClass == char.class)
1020        {
1021            if ( theString.length() != 1 )
1022            {
1023                throw new IllegalArgumentException JavaDoc( "not a character: " + theString );
1024            }
1025            
1026            result = new Character JavaDoc( theString.charAt( 0 ) );
1027        }
1028        else
1029        {
1030            
1031            final Class JavaDoc objectClass = PrimitiveClassToObjectClass( theClass );
1032            
1033            result = InstantiateObject( objectClass, theString );
1034        }
1035        
1036        return( result );
1037    }
1038    
1039    
1040    /**
1041        Given a Class, create a new instance with an empty constructor.
1042        Primitive types are instantiated as their equivalent Object forms.
1043        Any value is acceptable in the newly created object.
1044        
1045        @param inClass the class from which an instance should be instantiated
1046        @return the resulting Object
1047     */

1048        public static Object JavaDoc
1049    InstantiateDefault( final Class JavaDoc inClass )
1050        throws Exception JavaDoc
1051    {
1052        Object JavaDoc result = null;
1053        
1054        final Class JavaDoc objectClass = PrimitiveClassToObjectClass( inClass );
1055        
1056        if ( Number JavaDoc.class.isAssignableFrom( objectClass ) )
1057        {
1058            result = InstantiateFromString( objectClass, "0" );
1059        }
1060        else if ( objectClass == Boolean JavaDoc.class)
1061        {
1062            result = new Boolean JavaDoc( "true" );
1063        }
1064        else if ( objectClass == Character JavaDoc.class)
1065        {
1066            result = new Character JavaDoc( 'X' );
1067        }
1068        else if ( classIsArray( objectClass ) )
1069        {
1070            result = Array.newInstance( objectClass, 0 );
1071        }
1072        else if ( objectClass == Object JavaDoc.class )
1073        {
1074            result = new String JavaDoc( "anyObject" );
1075        }
1076        else if ( objectClass == String JavaDoc.class )
1077        {
1078            result = new String JavaDoc( "" );
1079        }
1080        else if ( objectClass == java.net.URL JavaDoc.class )
1081        {
1082            result = new java.net.URL JavaDoc( "http://www.sun.com" );
1083        }
1084        else if ( objectClass == java.net.URI JavaDoc.class )
1085        {
1086            result = new java.net.URI JavaDoc( "http://www.sun.com" );
1087        }
1088        else if ( classIsArray( inClass ) )
1089        {
1090            final int dimensions = 3;
1091            result = Array.newInstance( getInnerArrayElementClass( inClass ), dimensions );
1092        }
1093        else
1094        {
1095            result = objectClass.newInstance();
1096            //result = InstantiateFromString( objectClass, "0" );
1097
}
1098        return( result );
1099    }
1100    
1101    
1102     final static String JavaDoc [] sJavaLangTypes =
1103        { "Character", "Boolean", "Byte", "Short", "Integer", "Long", "Float", "Double", "String", "Object"};
1104     final static int sNumBaseTypes = Array.getLength( sJavaLangTypes );
1105     
1106    /**
1107        Expand an abbreviated classname into its true java name.
1108        
1109        Turn "Integer" into "java.lang.Integer", etc.
1110     */

1111        public static String JavaDoc
1112    ExpandClassName( final String JavaDoc name )
1113    {
1114        String JavaDoc fullName = name;
1115        
1116        final int numTypes = sNumBaseTypes;
1117        for( int i = 0; i < numTypes; ++i )
1118        {
1119            if ( name.equals( sJavaLangTypes[ i ] ) )
1120            {
1121                fullName = "java.lang." + name;
1122                break;
1123            }
1124        }
1125        
1126        if ( fullName == name ) // no match so far
1127
{
1128            if ( name.equals( "Number" ) )
1129            {
1130                fullName = "java.lang." + name;
1131            }
1132            else if ( name.equals( "BigDecimal" ) || name.equals( "BigInteger" ) )
1133            {
1134                fullName = "java.math." + name;
1135            }
1136            else if ( name.equals( "URL" ) || name.equals( "URI" ) )
1137            {
1138                fullName = "java.net." + name;
1139            }
1140            else if ( name.equals( "Date" ) )
1141            {
1142                fullName = "java.util." + name;
1143            }
1144            else if ( name.equals( "ObjectName" ) )
1145            {
1146                fullName = "javax.management." + name;
1147            }
1148            
1149        }
1150        
1151        return( fullName );
1152    }
1153    
1154    
1155
1156    /**
1157        Convert inner element to another type. Only works for arrays of Objects. Example:
1158        
1159        convertArrayClass( "[[[LObject;", "Long" ) =>[[[LLong;
1160        
1161        @param arrayClass
1162        @param newInnerType the desired Class of the innermost element
1163     */

1164        public static Class JavaDoc
1165    convertArrayClass( final Class JavaDoc arrayClass, final Class JavaDoc newInnerType )
1166        throws ClassNotFoundException JavaDoc
1167    {
1168        final String JavaDoc arrayClassname = arrayClass.getName();
1169        if ( ! arrayClassname.endsWith( ";" ) )
1170        {
1171            throw new IllegalArgumentException JavaDoc( "not an array of Object" );
1172        }
1173        
1174        final int innerNameBegin = 1 + arrayClassname.indexOf( "L" );
1175        
1176        final String JavaDoc newClassName = arrayClassname.substring( 0, innerNameBegin ) + newInnerType.getName() + ";";
1177        
1178        final Class JavaDoc newClass = getClassFromName( newClassName );
1179        
1180        return( newClass );
1181    }
1182    
1183    
1184    private static class MyClassLoader extends ClassLoader JavaDoc
1185    {
1186        MyClassLoader( )
1187        {
1188            this( Thread.currentThread().getContextClassLoader() );
1189        }
1190        
1191        MyClassLoader( ClassLoader JavaDoc cl )
1192        {
1193            super( cl );
1194        }
1195        
1196            public Package JavaDoc[]
1197        getPackages()
1198        {
1199            return( super.getPackages() );
1200        }
1201    }
1202    
1203        public static Package JavaDoc[]
1204    getPackages()
1205    {
1206        return( new MyClassLoader().getPackages() );
1207    }
1208    
1209        public static Package JavaDoc[]
1210    getPackages( ClassLoader JavaDoc cl )
1211    {
1212        return( new MyClassLoader( cl ).getPackages( ) );
1213    }
1214    
1215    
1216    /**
1217     */

1218        public static Object JavaDoc
1219    getFieldValue(
1220        final Class JavaDoc theInterface,
1221        final String JavaDoc name )
1222    {
1223        Object JavaDoc value = null;
1224        
1225        try
1226        {
1227            final Field JavaDoc field = theInterface.getField( name );
1228            value = field.get( theInterface );
1229        }
1230        catch( Exception JavaDoc e )
1231        {
1232            value = null;
1233        }
1234        
1235        return( value );
1236    }
1237    
1238        public static String JavaDoc
1239    stripPackagePrefix( final String JavaDoc classname )
1240    {
1241        final int index = classname.lastIndexOf( "." );
1242        
1243        String JavaDoc result = classname;
1244        if ( index > 0 )
1245        {
1246            result = classname.substring( index + 1, classname.length() );
1247        }
1248        
1249        return( result );
1250    };
1251    
1252    
1253        public static String JavaDoc
1254    getPackagePrefix( final String JavaDoc classname )
1255    {
1256        final int index = classname.lastIndexOf( "." );
1257        
1258        String JavaDoc result = classname;
1259        if ( index > 0 )
1260        {
1261            result = classname.substring( 0, index );
1262        }
1263        
1264        return( result );
1265    };
1266
1267}
1268
1269
1270
1271
1272
1273
1274
1275
Popular Tags