KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > typeconverter > StringArrayConverter


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.typeconverter;
4
5 /**
6  * Converts given object to String[].
7  * If object is an array than it is converted to String[] array.
8  * If object is not an array, new String[] array will be created with one
9  * element only: String of the given object.
10  */

11 public class StringArrayConverter implements TypeConverter {
12
13     public static String JavaDoc[] valueOf(Object JavaDoc value) {
14
15         if (value == null) {
16             return null;
17         }
18         Class JavaDoc type = value.getClass();
19         if (type.isArray() == false) {
20             return new String JavaDoc[] { value.toString() };
21         }
22
23         // handle arrays
24
if (type == String JavaDoc[].class) {
25             return (String JavaDoc[]) value;
26         }
27
28         Object JavaDoc[] values;
29         try {
30             values = (Object JavaDoc[]) value;
31         } catch (ClassCastException JavaDoc ccex) {
32             throw new TypeConversionException(ccex);
33         }
34
35         String JavaDoc[] result = new String JavaDoc[values.length];
36         for (int i = 0; i < values.length; i++) {
37             if (values[i] != null) {
38                 result[i] = values[i].toString();
39             }
40         }
41         return result;
42     }
43
44     public Object JavaDoc convert(Object JavaDoc value) {
45         return valueOf(value);
46     }
47     
48 }
49
Popular Tags