KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mortbay > util > TypeUtil


1 // ========================================================================
2
// $Id: TypeUtil.java,v 1.14 2005/12/06 00:51:40 gregwilkins Exp $
3
// Copyright 2002-2004 Mort Bay Consulting Pty. Ltd.
4
// ------------------------------------------------------------------------
5
// Licensed under the Apache License, Version 2.0 (the "License");
6
// you may not use this file except in compliance with the License.
7
// You may obtain a copy of the License at
8
// http://www.apache.org/licenses/LICENSE-2.0
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
// ========================================================================
15

16 package org.mortbay.util;
17
18 import java.lang.reflect.Constructor JavaDoc;
19 import java.lang.reflect.InvocationTargetException JavaDoc;
20 import java.lang.reflect.Method JavaDoc;
21 import java.util.HashMap JavaDoc;
22
23 import org.apache.commons.logging.Log;
24 import org.mortbay.log.LogFactory;
25
26 /* ------------------------------------------------------------ */
27 /** TYPE Utilities.
28  * Provides various static utiltiy methods for manipulating types and their
29  * string representations.
30  *
31  * @since Jetty 4.1
32  * @version $Revision: 1.14 $
33  * @author Greg Wilkins (gregw)
34  */

35 public class TypeUtil
36 {
37     private static Log log = LogFactory.getLog(TypeUtil.class);
38
39     /* ------------------------------------------------------------ */
40     private static final HashMap JavaDoc name2Class=new HashMap JavaDoc();
41     static
42     {
43         name2Class.put("boolean",java.lang.Boolean.TYPE);
44         name2Class.put("byte",java.lang.Byte.TYPE);
45         name2Class.put("char",java.lang.Character.TYPE);
46         name2Class.put("double",java.lang.Double.TYPE);
47         name2Class.put("float",java.lang.Float.TYPE);
48         name2Class.put("int",java.lang.Integer.TYPE);
49         name2Class.put("long",java.lang.Long.TYPE);
50         name2Class.put("short",java.lang.Short.TYPE);
51         name2Class.put("void",java.lang.Void.TYPE);
52         
53         name2Class.put("java.lang.Boolean.TYPE",java.lang.Boolean.TYPE);
54         name2Class.put("java.lang.Byte.TYPE",java.lang.Byte.TYPE);
55         name2Class.put("java.lang.Character.TYPE",java.lang.Character.TYPE);
56         name2Class.put("java.lang.Double.TYPE",java.lang.Double.TYPE);
57         name2Class.put("java.lang.Float.TYPE",java.lang.Float.TYPE);
58         name2Class.put("java.lang.Integer.TYPE",java.lang.Integer.TYPE);
59         name2Class.put("java.lang.Long.TYPE",java.lang.Long.TYPE);
60         name2Class.put("java.lang.Short.TYPE",java.lang.Short.TYPE);
61         name2Class.put("java.lang.Void.TYPE",java.lang.Void.TYPE);
62
63         name2Class.put("java.lang.Boolean",java.lang.Boolean JavaDoc.class);
64         name2Class.put("java.lang.Byte",java.lang.Byte JavaDoc.class);
65         name2Class.put("java.lang.Character",java.lang.Character JavaDoc.class);
66         name2Class.put("java.lang.Double",java.lang.Double JavaDoc.class);
67         name2Class.put("java.lang.Float",java.lang.Float JavaDoc.class);
68         name2Class.put("java.lang.Integer",java.lang.Integer JavaDoc.class);
69         name2Class.put("java.lang.Long",java.lang.Long JavaDoc.class);
70         name2Class.put("java.lang.Short",java.lang.Short JavaDoc.class);
71
72         name2Class.put("Boolean",java.lang.Boolean JavaDoc.class);
73         name2Class.put("Byte",java.lang.Byte JavaDoc.class);
74         name2Class.put("Character",java.lang.Character JavaDoc.class);
75         name2Class.put("Double",java.lang.Double JavaDoc.class);
76         name2Class.put("Float",java.lang.Float JavaDoc.class);
77         name2Class.put("Integer",java.lang.Integer JavaDoc.class);
78         name2Class.put("Long",java.lang.Long JavaDoc.class);
79         name2Class.put("Short",java.lang.Short JavaDoc.class);
80
81         name2Class.put(null,java.lang.Void.TYPE);
82         name2Class.put("string",java.lang.String JavaDoc.class);
83         name2Class.put("String",java.lang.String JavaDoc.class);
84         name2Class.put("java.lang.String",java.lang.String JavaDoc.class);
85     }
86     
87     /* ------------------------------------------------------------ */
88     private static final HashMap JavaDoc class2Name=new HashMap JavaDoc();
89     static
90     {
91         class2Name.put(java.lang.Boolean.TYPE,"boolean");
92         class2Name.put(java.lang.Byte.TYPE,"byte");
93         class2Name.put(java.lang.Character.TYPE,"char");
94         class2Name.put(java.lang.Double.TYPE,"double");
95         class2Name.put(java.lang.Float.TYPE,"float");
96         class2Name.put(java.lang.Integer.TYPE,"int");
97         class2Name.put(java.lang.Long.TYPE,"long");
98         class2Name.put(java.lang.Short.TYPE,"short");
99         class2Name.put(java.lang.Void.TYPE,"void");
100
101         class2Name.put(java.lang.Boolean JavaDoc.class,"java.lang.Boolean");
102         class2Name.put(java.lang.Byte JavaDoc.class,"java.lang.Byte");
103         class2Name.put(java.lang.Character JavaDoc.class,"java.lang.Character");
104         class2Name.put(java.lang.Double JavaDoc.class,"java.lang.Double");
105         class2Name.put(java.lang.Float JavaDoc.class,"java.lang.Float");
106         class2Name.put(java.lang.Integer JavaDoc.class,"java.lang.Integer");
107         class2Name.put(java.lang.Long JavaDoc.class,"java.lang.Long");
108         class2Name.put(java.lang.Short JavaDoc.class,"java.lang.Short");
109         
110         class2Name.put(null,"void");
111         name2Class.put(java.lang.String JavaDoc.class,"java.lang.String");
112     }
113     
114     /* ------------------------------------------------------------ */
115     private static final HashMap JavaDoc class2Value=new HashMap JavaDoc();
116     static
117     {
118         try
119         {
120             Class JavaDoc[] s ={java.lang.String JavaDoc.class};
121             
122             class2Value.put(java.lang.Boolean.TYPE,
123                            java.lang.Boolean JavaDoc.class.getMethod("valueOf",s));
124             class2Value.put(java.lang.Byte.TYPE,
125                            java.lang.Byte JavaDoc.class.getMethod("valueOf",s));
126             class2Value.put(java.lang.Double.TYPE,
127                            java.lang.Double JavaDoc.class.getMethod("valueOf",s));
128             class2Value.put(java.lang.Float.TYPE,
129                            java.lang.Float JavaDoc.class.getMethod("valueOf",s));
130             class2Value.put(java.lang.Integer.TYPE,
131                            java.lang.Integer JavaDoc.class.getMethod("valueOf",s));
132             class2Value.put(java.lang.Long.TYPE,
133                            java.lang.Long JavaDoc.class.getMethod("valueOf",s));
134             class2Value.put(java.lang.Short.TYPE,
135                            java.lang.Short JavaDoc.class.getMethod("valueOf",s));
136
137             class2Value.put(java.lang.Boolean JavaDoc.class,
138                            java.lang.Boolean JavaDoc.class.getMethod("valueOf",s));
139             class2Value.put(java.lang.Byte JavaDoc.class,
140                            java.lang.Byte JavaDoc.class.getMethod("valueOf",s));
141             class2Value.put(java.lang.Double JavaDoc.class,
142                            java.lang.Double JavaDoc.class.getMethod("valueOf",s));
143             class2Value.put(java.lang.Float JavaDoc.class,
144                            java.lang.Float JavaDoc.class.getMethod("valueOf",s));
145             class2Value.put(java.lang.Integer JavaDoc.class,
146                            java.lang.Integer JavaDoc.class.getMethod("valueOf",s));
147             class2Value.put(java.lang.Long JavaDoc.class,
148                            java.lang.Long JavaDoc.class.getMethod("valueOf",s));
149             class2Value.put(java.lang.Short JavaDoc.class,
150                            java.lang.Short JavaDoc.class.getMethod("valueOf",s));
151         }
152         catch(Exception JavaDoc e)
153         {
154             log.warn(LogSupport.EXCEPTION,e);
155         }
156     }
157
158     /* ------------------------------------------------------------ */
159     private static Class JavaDoc[] stringArg = { java.lang.String JavaDoc.class };
160     
161     /* ------------------------------------------------------------ */
162     private static int intCacheSize=
163         Integer.getInteger("org.mortbay.util.TypeUtil.IntegerCacheSize",600).intValue();
164     private static Integer JavaDoc[] integerCache = new Integer JavaDoc[intCacheSize];
165     private static String JavaDoc[] integerStrCache = new String JavaDoc[intCacheSize];
166     private static Integer JavaDoc minusOne = new Integer JavaDoc(-1);
167     
168     /* ------------------------------------------------------------ */
169     /** Class from a canonical name for a type.
170      * @param name A class or type name.
171      * @return A class , which may be a primitive TYPE field..
172      */

173     public static Class JavaDoc fromName(String JavaDoc name)
174     {
175         return (Class JavaDoc)name2Class.get(name);
176     }
177     
178     /* ------------------------------------------------------------ */
179     /** Canonical name for a type.
180      * @param type A class , which may be a primitive TYPE field.
181      * @return Canonical name.
182      */

183     public static String JavaDoc toName(Class JavaDoc type)
184     {
185         return (String JavaDoc)class2Name.get(type);
186     }
187     
188     /* ------------------------------------------------------------ */
189     /** Convert String value to instance.
190      * @param type The class of the instance, which may be a primitive TYPE field.
191      * @param value The value as a string.
192      * @return The value as an Object.
193      */

194     public static Object JavaDoc valueOf(Class JavaDoc type, String JavaDoc value)
195     {
196         try
197         {
198             if (type.equals(java.lang.String JavaDoc.class))
199                 return value;
200             
201             Method JavaDoc m = (Method JavaDoc)class2Value.get(type);
202             if (m!=null)
203                 return m.invoke(null,new Object JavaDoc[] {value});
204
205             if (type.equals(java.lang.Character.TYPE) ||
206                 type.equals(java.lang.Character JavaDoc.class))
207                 return new Character JavaDoc(value.charAt(0));
208
209             Constructor JavaDoc c = type.getConstructor(stringArg);
210             return c.newInstance(new Object JavaDoc[] {value});
211         }
212         catch(NoSuchMethodException JavaDoc e)
213         {
214             LogSupport.ignore(log,e);
215         }
216         catch(IllegalAccessException JavaDoc e)
217         {
218             LogSupport.ignore(log,e);
219         }
220         catch(InstantiationException JavaDoc e)
221         {
222             LogSupport.ignore(log,e);
223         }
224         catch(InvocationTargetException JavaDoc e)
225         {
226             if (e.getTargetException() instanceof Error JavaDoc)
227                 throw (Error JavaDoc)(e.getTargetException());
228             LogSupport.ignore(log,e);
229         }
230         return null;
231     }
232     
233     /* ------------------------------------------------------------ */
234     /** Convert String value to instance.
235      * @param type classname or type (eg int)
236      * @param value The value as a string.
237      * @return The value as an Object.
238      */

239     public static Object JavaDoc valueOf(String JavaDoc type, String JavaDoc value)
240     {
241         return valueOf(fromName(type),value);
242     }
243     
244     /* ------------------------------------------------------------ */
245     /** Convert int to Integer using cache.
246      */

247     public static Integer JavaDoc newInteger(int i)
248     {
249         if (i>=0 && i<intCacheSize)
250         {
251             if (integerCache[i]==null)
252                 integerCache[i]=new Integer JavaDoc(i);
253             return integerCache[i];
254         }
255         else if (i==-1)
256             return minusOne;
257         return new Integer JavaDoc(i);
258     }
259
260     
261     /* ------------------------------------------------------------ */
262     /** Convert int to String using cache.
263      */

264     public static String JavaDoc toString(int i)
265     {
266         if (i>=0 && i<intCacheSize)
267         {
268             if (integerStrCache[i]==null)
269                 integerStrCache[i]=Integer.toString(i);
270             return integerStrCache[i];
271         }
272         else if (i==-1)
273             return "-1";
274         return Integer.toString(i);
275     }
276
277
278     /* ------------------------------------------------------------ */
279     /** Parse an int from a substring.
280      * Negative numbers are not handled.
281      * @param s String
282      * @param offset Offset within string
283      * @param length Length of integer or -1 for remainder of string
284      * @param base base of the integer
285      * @exception NumberFormatException
286      */

287     public static int parseInt(String JavaDoc s, int offset, int length, int base)
288         throws NumberFormatException JavaDoc
289     {
290         int value=0;
291
292         if (length<0)
293             length=s.length()-offset;
294
295         for (int i=0;i<length;i++)
296         {
297             char c=s.charAt(offset+i);
298             
299             int digit=c-'0';
300             if (digit<0 || digit>=base || digit>=10)
301             {
302                 digit=10+c-'A';
303                 if (digit<10 || digit>=base)
304                     digit=10+c-'a';
305             }
306             if (digit<0 || digit>=base)
307                 throw new NumberFormatException JavaDoc(s.substring(offset,offset+length));
308             value=value*base+digit;
309         }
310         return value;
311     }
312
313     /* ------------------------------------------------------------ */
314     public static byte[] parseBytes(String JavaDoc s, int base)
315     {
316         byte[] bytes=new byte[s.length()/2];
317         for (int i=0;i<s.length();i+=2)
318             bytes[i/2]=(byte)TypeUtil.parseInt(s,i,2,base);
319         return bytes;
320     }
321
322     /* ------------------------------------------------------------ */
323     public static String JavaDoc toString(byte[] bytes, int base)
324     {
325         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
326         for (int i=0;i<bytes.length;i++)
327         {
328             int bi=0xff&bytes[i];
329             int c='0'+(bi/base)%base;
330             if (c>'9')
331                 c= 'a'+(c-'0'-10);
332             buf.append((char)c);
333             c='0'+bi%base;
334             if (c>'9')
335                 c= 'a'+(c-'0'-10);
336             buf.append((char)c);
337         }
338         return buf.toString();
339     }
340
341     /* ------------------------------------------------------------ */
342     /**
343      * @param b An ASCII encoded character 0-9 a-f A-F
344      * @return The byte value of the character 0-16.
345      */

346     public static byte convertHexDigit( byte b )
347     {
348         if ((b >= '0') && (b <= '9')) return (byte)(b - '0');
349         if ((b >= 'a') && (b <= 'f')) return (byte)(b - 'a' + 10);
350         if ((b >= 'A') && (b <= 'F')) return (byte)(b - 'A' + 10);
351         return 0;
352     }
353
354     /* ------------------------------------------------------------ */
355     public static char toHexChar(int b)
356     {
357         return (char)(b<10?('0'+b):('A'+b-10));
358     }
359     
360     /* ------------------------------------------------------------ */
361     public static String JavaDoc toHexString(byte[] b)
362     {
363         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
364         for (int i=0;i<b.length;i++)
365         {
366             int bi=0xff&b[i];
367             int c='0'+(bi/16)%16;
368             if (c>'9')
369                 c= 'A'+(c-'0'-10);
370             buf.append((char)c);
371             c='0'+bi%16;
372             if (c>'9')
373                 c= 'a'+(c-'0'-10);
374             buf.append((char)c);
375         }
376         return buf.toString();
377     }
378     
379     /* ------------------------------------------------------------ */
380     public static String JavaDoc toHexString(byte[] b,int offset,int length)
381     {
382         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
383         for (int i=offset;i<offset+length;i++)
384         {
385             int bi=0xff&b[i];
386             int c='0'+(bi/16)%16;
387             if (c>'9')
388                 c= 'A'+(c-'0'-10);
389             buf.append((char)c);
390             c='0'+bi%16;
391             if (c>'9')
392                 c= 'a'+(c-'0'-10);
393             buf.append((char)c);
394         }
395         return buf.toString();
396     }
397     
398     /* ------------------------------------------------------------ */
399     public static byte[] fromHexString(String JavaDoc s)
400     {
401         if (s.length()%2!=0)
402             throw new IllegalArgumentException JavaDoc(s);
403         byte[] array = new byte[s.length()/2];
404         for (int i=0;i<array.length;i++)
405         {
406             int b = Integer.parseInt(s.substring(i*2,i*2+2),16);
407             array[i]=(byte)(0xff&b);
408         }
409         return array;
410     }
411     
412
413     public static void dump(Class JavaDoc c)
414     {
415         System.err.println("Dump: "+c);
416         dump(c.getClassLoader());
417     }
418
419     public static void dump(ClassLoader JavaDoc cl)
420     {
421         System.err.println("Dump Loaders:");
422         while(cl!=null)
423         {
424             System.err.println(" loader "+cl);
425             cl = cl.getParent();
426         }
427     }
428 }
429
Popular Tags