KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > bean > converters > BooleanConverter


1 package jodd.bean.converters;
2
3 /**
4  * Converts given object to Boolean. Given object (if not already instance of
5  * Boolean) is first converted to String and then analyzed.
6  */

7 public class BooleanConverter implements jodd.bean.Converter {
8
9     public Object convert(Object value) {
10         if (value == null) {
11             return (Boolean) null;
12         }
13         if (value instanceof Boolean) {
14             return value;
15         }
16         try {
17             String stringValue = value.toString();
18             if (stringValue.equalsIgnoreCase("yes") ||
19                 stringValue.equalsIgnoreCase("y") ||
20                 stringValue.equalsIgnoreCase("true") ||
21                 stringValue.equalsIgnoreCase("on") ||
22                 stringValue.equalsIgnoreCase("1")) {
23                 return Boolean.TRUE;
24             } else if (stringValue.equalsIgnoreCase("no") ||
25                        stringValue.equalsIgnoreCase("n") ||
26                        stringValue.equalsIgnoreCase("false") ||
27                        stringValue.equalsIgnoreCase("off") ||
28                        stringValue.equalsIgnoreCase("0")) {
29                 return Boolean.FALSE;
30             } else {
31                 throw new IllegalArgumentException("Boolean conversion for " + value + " failed.");
32             }
33         } catch (ClassCastException e) {
34             throw new IllegalArgumentException("Boolean cast for " + value + " failed.");
35         }
36     }
37 }
38
Popular Tags