1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.util.internal;
17
18 import java.util.ArrayList;
19 import java.util.List;
20 import java.util.regex.Pattern;
21
22
23
24
25
26 public final class ConversionUtil {
27
28
29
30
31 public static int toInt(Object value) {
32 if (value instanceof Number) {
33 return ((Number) value).intValue();
34 } else {
35 return Integer.parseInt(String.valueOf(value));
36 }
37 }
38
39
40
41
42 public static boolean toBoolean(Object value) {
43 if (value instanceof Boolean) {
44 return ((Boolean) value).booleanValue();
45 }
46 if (value instanceof Number) {
47 return ((Number) value).intValue() != 0;
48 } else {
49 String s = String.valueOf(value);
50 if (s.length() == 0) {
51 return false;
52 }
53
54 try {
55 return Integer.parseInt(s) != 0;
56 } catch (NumberFormatException e) {
57
58 }
59
60 switch (Character.toUpperCase(s.charAt(0))) {
61 case 'T': case 'Y':
62 return true;
63 }
64 return false;
65 }
66 }
67
68 private static final Pattern ARRAY_DELIM = Pattern.compile("[, \\t\\n\\r\\f\\e\\a]");
69
70
71
72
73 public static String[] toStringArray(Object value) {
74 if (value instanceof String[]) {
75 return (String[]) value;
76 }
77
78 if (value instanceof Iterable<?>) {
79 List<String> answer = new ArrayList<String>();
80 for (Object v: (Iterable<?>) value) {
81 if (v == null) {
82 answer.add(null);
83 } else {
84 answer.add(String.valueOf(v));
85 }
86 }
87 return answer.toArray(new String[answer.size()]);
88 }
89
90 return ARRAY_DELIM.split(String.valueOf(value));
91 }
92
93 private static final String[] INTEGERS = {
94 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
95 "10", "11", "12", "13", "14", "15",
96 };
97
98 public static String toString(int value) {
99 if (value >= 0 && value < INTEGERS.length) {
100 return INTEGERS[value];
101 } else {
102 return Integer.toString(value);
103 }
104 }
105
106 private ConversionUtil() {
107
108 }
109 }