KickJava   Java API By Example, From Geeks To Geeks.

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


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 package com.sun.appserv.management.util.misc;
24
25
26 import java.util.List JavaDoc;
27 import java.util.Map JavaDoc;
28 import java.util.Set JavaDoc;
29 import java.util.SortedSet JavaDoc;
30 import java.util.Collection JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.Hashtable JavaDoc;
33
34 import java.io.Serializable JavaDoc;
35
36 import javax.management.ObjectName JavaDoc;
37
38
39 /**
40     This utility class contains two types of methods:
41     <ul>
42     <li>Methods to cast Collection/List/Set/Map/etc to a more strongly-typed
43     generic type;</li>
44     <li>Methods to verify the types of elements within the above.</li>
45     </ul>
46     <p>
47     Due to the way in which generic types are implemented in JDK 1.5, coupled
48     with the fact that both generic and non-generic code need to coexist,
49     there exist a variety of cases in which casts cannot be avoided. However,
50     performing such cast generates compiler warnings which cannot be eliminated,
51     and which thus produce clutter which makes it hard to recognize
52     other warnings during compilation.
53     <p>
54     The casting methods here localize the aforementioned compiler warnings to this
55     file thus allowing code elsewhere to compile "cleanly" (eg without warnings).
56     <p>
57     Clients should use the casting routines <b>only when there is
58     no other appropriate solution</b>.
59     For example, consider a caller of non-generic code method getStuff():
60     <pre>Map getStuff()</pre>
61     The javadoc for getStuff() specifies that the keys and
62     values of the Map are java.lang.String.
63     The caller would like to declare:
64     <pre>
65     final Map&lt;String,String> m = getStuff();
66     </pre>
67     But this will generate a compiler warning. To avoid this compiler warning,
68     the code should be written as follows:
69     <pre>
70     final Map&lt;String,String> m = TypeCast.asMap( getStuff() );
71     </pre>
72     If there is any doubt as to the correct contents of a
73     Collection/List/Set/Map, use the appropriate {@link #checkCollection},
74     {@link #checkMap}, {@link #checkList} method.
75     <p>
76     Due to the way generics are implemented, an explicit call is needed with
77     a specific class in order to do so; this is why the as() methods do
78     not already perform that check. Following the above example, we would write:
79     <code>TypeCast.checkCompatible(m, String.class, String.class)</code>
80     <p>
81     Naturally checking the keys and values of the Map is far more expensive
82     than a simple cast, but if the contents are unclear, {@link #checkMap}
83     is strongly advised over {@link #asMap}. The same holds true for the
84     Collection, Set, and List variants of these methods.
85     Most casts can be handled appropriately through the appropriate use
86     of generic types.
87  */

88 public final class TypeCast
89 {
90     
91     /**
92         The caller should take appropriate care that the type of element
93         is correct, and may want to call {@link #checkCollection} instead
94         if there is any doubt.
95         @param o the Object, which must be a {@link Collection}
96         @return Collection<T>
97      */

98     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
99
public static <T> Collection JavaDoc<T>
100     asCollection( final Object JavaDoc o )
101     {
102         return (Collection JavaDoc<T>)Collection JavaDoc.class.cast( o );
103     }
104     
105     /**
106         The caller should take appropriate care that the type of element
107         is correct, and may want to call {@link #checkCollection} instead if there is
108         any doubt.
109         @return Collection<T extends Serializable>
110      */

111         public static <T extends Serializable JavaDoc> Collection JavaDoc<T>
112     asSerializableCollection( final Object JavaDoc c )
113     {
114         final Collection JavaDoc<T> result = asCollection( c );
115         checkSerializable( result );
116         return result;
117     }
118     
119     /**
120         The caller should take appropriate care that the type of keys/values
121         is correct, and may want to call {@link #checkMap} instead if there is
122         any doubt.
123         @return Map<K,V>
124         @return Map<K extends Serializable,V extends Serializable>
125      */

126     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
127
public static <K,V> Map JavaDoc<K,V>
128     asMap( final Object JavaDoc m)
129     {
130         return (Map JavaDoc<K,V>)Map JavaDoc.class.cast( m );
131     }
132     
133     /**
134         The caller should take appropriate care that the type of keys/values
135         is correct, and may want to call {@link #checkSerializable} instead if there is
136         any doubt.
137         @return Map<K extends Serializable,V extends Serializable>
138      */

139         public static <K extends Serializable JavaDoc,V extends Serializable JavaDoc> Map JavaDoc<K,V>
140     asSerializableMap( final Object JavaDoc m)
141     {
142         final Map JavaDoc<K,V> result = asMap( m );
143         checkSerializable( result );
144         
145         return result;
146     }
147     
148     /**
149         The caller should take appropriate care that the type of element
150         is correct, and may want to call {@link #checkMap} instead if there is
151         any doubt.
152         @return Hashtable<K,V>
153      */

154     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
155
public static <K,V> Hashtable JavaDoc<K,V>
156     asHashtable( final Object JavaDoc o )
157     {
158         return (Hashtable JavaDoc<K,V>)Hashtable JavaDoc.class.cast( o );
159     }
160     
161     /**
162         The caller should take appropriate care that the type of element
163         is correct, and may want to call {@link #checkList} instead if there is
164         any doubt.
165         @return List<T>
166      */

167     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
168
public static <T> List JavaDoc<T>
169     asList( final Object JavaDoc list)
170     {
171         return (List JavaDoc<T>)List JavaDoc.class.cast( list );
172     }
173     
174     /**
175         The caller should take appropriate care that the type of element
176         is correct, and may want to call{@link #checkList} instead if there is
177         any doubt.
178         @return List<T extends Serializable>
179      */

180         public static <T extends Serializable JavaDoc> List JavaDoc<T>
181     asSerializableList( final Object JavaDoc list)
182     {
183         final List JavaDoc<T> result = asList( list );
184         checkSerializable( result );
185         return result;
186     }
187     
188     /**
189         The caller should take appropriate care that the type of element
190         is correct, and may want to call {@link #checkSet} instead if there is
191         any doubt.
192         @return Set<T>
193      */

194     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
195
public static <T> Set JavaDoc<T>
196     asSet( final Object JavaDoc s )
197     {
198         return (Set JavaDoc<T>)Set JavaDoc.class.cast( s );
199     }
200     
201     /**
202         The caller should take appropriate care that the type of element
203         is correct, and may want to call {@link #checkSet} instead if there is
204         any doubt.
205         @return Set<T>
206      */

207     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
208
public static <T> SortedSet JavaDoc<T>
209     asSortedSet( final Object JavaDoc s )
210     {
211         return (SortedSet JavaDoc<T>)Set JavaDoc.class.cast( s );
212     }
213     
214     /**
215         The caller should take appropriate care that the type of element
216         is correct, and may want to call {@link #checkSet} instead if there is
217         any doubt.
218         @return Set<T extends Serializable>
219      */

220         public static <T extends Serializable JavaDoc> Set JavaDoc<T>
221     asSerializableSet( final Object JavaDoc s )
222     {
223         final Set JavaDoc<T> result = asSet( s );
224         checkSerializable( result );
225         return result;
226     }
227     
228     
229     /**
230         The caller should take appropriate care that the type is correct.
231         @return Class<T>
232      */

233     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
234
public static <T> Class JavaDoc<T>
235     asClass( final Class JavaDoc<?> c )
236     {
237         if ( ! ( c instanceof Class JavaDoc ) )
238         {
239             throw new IllegalArgumentException JavaDoc( "" + c );
240         }
241         
242         return (Class JavaDoc<T>)Class JavaDoc.class.cast( c );
243     }
244     
245     
246     /**
247         The caller should take appropriate care that the type is correct.
248         @return Class<T>
249      */

250     @SuppressWarnings JavaDoc("unchecked") // inherent/unavoidable for this method
251
public static <T> T[]
252     asArray( final Object JavaDoc o )
253     {
254         return (T[])Object JavaDoc[].class.cast( o );
255     }
256     
257     
258     /**
259         Verify that all elements implement java.io.Serializable
260         @throws ClassCastException
261      */

262         public static void
263     checkSerializable( final Object JavaDoc[] a )
264     {
265         for( final Object JavaDoc o : a )
266         {
267             checkSerializable( o );
268         }
269     }
270     
271     /**
272         Verify that all elements implement java.io.Serializable
273         @throws ClassCastException
274      */

275         public static void
276     checkSerializableElements( final Collection JavaDoc<?> l )
277     {
278         for( final Object JavaDoc o : l )
279         {
280             checkSerializable( o );
281         }
282     }
283     
284     
285     /**
286         Verify that all elements implement java.io.Serializable
287         @throws ClassCastException
288      */

289         public static Collection JavaDoc<Serializable JavaDoc>
290     checkSerializable( final Collection JavaDoc<?> l )
291     {
292         checkSerializable( l, true );
293         return asCollection( l );
294     }
295     
296     /**
297         Verify that all elements implement java.io.Serializable
298         @param l the Collection
299         @param collectionItself if true, the Collection itself is additionally checked,
300         if false only the elements are checked.
301         @throws ClassCastException
302      */

303         public static Collection JavaDoc<Serializable JavaDoc>
304     checkSerializable( final Collection JavaDoc<?> l, boolean collectionItself )
305     {
306         if ( collectionItself )
307         {
308             checkSerializable( (Object JavaDoc)l );
309         }
310         
311         checkSerializableElements( l );
312         
313         return asCollection( l );
314     }
315     
316     /**
317         Verify that the Map itself, and all keys and values
318         implement java.io.Serializable
319         @throws ClassCastException
320      */

321         public static Map JavaDoc<Serializable JavaDoc,Serializable JavaDoc>
322     checkSerializable( final Map JavaDoc<?,?> m )
323     {
324         checkSerializable( (Object JavaDoc)m );
325         
326         // the key set used by HashMap isn't Serializable; apparently
327
// HashMap serializes itself properly, but not by serializing
328
// the key set directly. So if the Map is Serializable, we
329
// can't necessarily constrain the key set and value set to be so,
330
// since it's up to the Map to serialize properly.
331
checkSerializable( m.keySet(), false);
332         checkSerializable( m.values(), false);
333         
334         return asMap( m );
335     }
336     
337     /**
338         Verify that the Object implements java.io.Serializable.
339         @throws ClassCastException
340      */

341         public static Serializable JavaDoc
342     checkSerializable( final Object JavaDoc o )
343     {
344         if ( (o != null) && ! (o instanceof Serializable JavaDoc) )
345         {
346             throw new ClassCastException JavaDoc( "Object not Serializable, class = " + o.getClass().getName() );
347         }
348         
349         return Serializable JavaDoc.class.cast( o );
350     }
351     
352
353     //-------------
354

355     /**
356         Verify that the elements are all assignable to an object of the
357         specified class.
358         @param theClass the Class which the element must extend
359         @param c
360         @throws ClassCastException
361      */

362         public static <T> Collection JavaDoc<T>
363     checkCollection( final Collection JavaDoc<?> c, final Class JavaDoc<T> theClass )
364     {
365         if ( c != null )
366         {
367             for( final Object JavaDoc o : c )
368             {
369                 checkObject( o, theClass );
370             }
371         }
372         
373         return asCollection(c);
374     }
375     
376     /**
377         Verify that the elements are all assignable to an object of the
378         specified class.
379         @param l the list
380         @param theClass the Class which the element must extend
381         @throws ClassCastException
382      */

383         public static <T> List JavaDoc<T>
384     checkList( final List JavaDoc<?> l, final Class JavaDoc<T> theClass )
385     {
386         if ( l != null )
387         {
388             for( final Object JavaDoc o : l )
389             {
390                 checkObject( o, theClass );
391             }
392         }
393         
394         return asList(l);
395     }
396     
397     /**
398         Verify that the elements are all assignable to an object of the
399         specified class.
400         @param s
401         @param theClass the Class which the element must extend
402         @throws ClassCastException
403      */

404         public static <T> Set JavaDoc<T>
405     checkSet( final Set JavaDoc<?> s, final Class JavaDoc<T> theClass )
406     {
407         if ( s != null )
408         {
409             for( final Object JavaDoc o : s )
410             {
411                 checkObject( o, theClass );
412             }
413         }
414         
415         return asSet(s);
416     }
417     
418     /**
419         Verify that the elements are all assignable to an object of the
420         specified class.
421         @param m
422         @param keyClass the Class which keys must extend
423         @param valueClass the Class which values must extend
424         @throws ClassCastException
425      */

426         public static <K,V> Map JavaDoc<K,V>
427     checkMap(
428         final Map JavaDoc<?,?> m,
429         final Class JavaDoc<K> keyClass,
430         final Class JavaDoc<V> valueClass )
431     {
432         if ( m != null )
433         {
434             checkSet( m.keySet(), keyClass );
435             checkCollection( m.values(), valueClass );
436         }
437         
438         return asMap( m );
439     }
440     
441     /**
442         Verify that the Object is assignable to an object of the
443         specified class.
444         @param theClass the Class
445         @param o the Object
446         @throws ClassCastException
447      */

448     @SuppressWarnings JavaDoc("unchecked")
449         public static <T> T
450     checkObject( final Object JavaDoc o, final Class JavaDoc<T> theClass )
451     {
452         if ( o != null && ! theClass.isAssignableFrom( o.getClass() ) )
453         {
454             throw new ClassCastException JavaDoc( "Object of class " + o.getClass().getName() +
455                 " not assignment compatible with: " + theClass.getName() );
456         }
457         return (T)o;
458     }
459     
460     /**
461         Verify that the elements are all assignable to an object of the
462         specified class.
463         @param theClass the Class which the element must extend
464         @param a the Array of elements
465         @throws ClassCastException
466      */

467         public static <T> void
468     checkArray( final Object JavaDoc[] a, final Class JavaDoc<T> theClass )
469     {
470         for( final Object JavaDoc o : a )
471         {
472             checkObject( o, theClass );
473         }
474     }
475     
476     
477     /**
478         Create a checked Collection<String>, first verifying that all elements
479         are in fact String.
480         @param c the Collection
481         @throws ClassCastException
482      */

483         public static Collection JavaDoc<String JavaDoc>
484     checkedStringCollection( final Collection JavaDoc<?> c )
485     {
486         return checkedCollection( c, String JavaDoc.class );
487     }
488     
489     /**
490         Create a checked Set<String>, first verifying that all elements
491         are in fact String.
492         @param s the Set
493         @throws ClassCastException
494      */

495         public static Set JavaDoc<String JavaDoc>
496     checkedStringSet( final Set JavaDoc<?> s )
497     {
498         return checkedSet( s, String JavaDoc.class );
499     }
500     
501     /**
502         Create a checked List<String>, first verifying that all elements
503         are in fact String.
504         @param l the List
505         @throws ClassCastException
506      */

507         public static List JavaDoc<String JavaDoc>
508     checkedStringList( final List JavaDoc<?> l )
509     {
510         return checkedList( l, String JavaDoc.class );
511     }
512     
513     /**
514         Create a checked Map<String,String>, first verifying that all keys
515         and values are in fact String.
516         @param m the Map
517         @throws ClassCastException
518      */

519         public static Map JavaDoc<String JavaDoc,String JavaDoc>
520     checkedStringMap( final Map JavaDoc<?,?> m )
521     {
522         return checkedMap( m, String JavaDoc.class, String JavaDoc.class);
523     }
524     
525     
526     
527     /**
528         Create a checked Collection<String>, first verifying that all elements
529         are in fact String.
530         @param c the Collection
531         @throws ClassCastException
532      */

533         public static <T> Collection JavaDoc<T>
534     checkedCollection( final Collection JavaDoc<?> c, final Class JavaDoc<T> theClass )
535     {
536         final Collection JavaDoc<T> cc = checkCollection( c, theClass );
537         return Collections.checkedCollection( cc, theClass );
538     }
539     
540     /**
541         Create a checked Set<String>, first verifying that all elements
542         are in fact String.
543         @param s the Set
544         @throws ClassCastException
545      */

546         public static <T> Set JavaDoc<T>
547     checkedSet( final Set JavaDoc<?> s, final Class JavaDoc<T> theClass )
548     {
549         final Set JavaDoc<T> cs = checkSet( s, theClass );
550         return Collections.checkedSet( cs, theClass );
551     }
552     
553     /**
554         Create a checked List<String>, first verifying that all elements
555         are in fact String.
556         @param l the List
557         @throws ClassCastException
558      */

559         public static <T> List JavaDoc<T>
560     checkedList( final List JavaDoc<?> l, final Class JavaDoc<T> theClass )
561     {
562         final List JavaDoc<T> cl = checkList( l, theClass );
563         return Collections.checkedList( cl, theClass );
564     }
565     
566     /**
567         Create a checked Map<String,String>, first verifying that all keys
568         and values are in fact String.
569         @param m the Map
570         @throws ClassCastException
571      */

572         public static <K,V> Map JavaDoc<K,V>
573     checkedMap( final Map JavaDoc<?,?> m, final Class JavaDoc<K> keyClass, final Class JavaDoc<V> valueClass )
574     {
575         final Map JavaDoc<K,V> cm = checkMap( m, keyClass, valueClass );
576         return Collections.checkedMap( cm, keyClass, valueClass );
577     }
578 }
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
Popular Tags