1 16 package org.apache.commons.jexl.util; 17 18 24 public class Coercion { 25 26 32 public static Boolean coerceBoolean(Object val) { 33 if (val == null) { 34 return Boolean.FALSE; 35 } else if (val instanceof Boolean ) { 36 return (Boolean ) val; 37 } else if (val instanceof String ) { 38 return Boolean.valueOf((String ) val); 39 } 40 return null; 41 } 42 43 50 public static Integer coerceInteger(Object val) 51 throws Exception { 52 if (val == null) { 53 return new Integer (0); 54 } else if (val instanceof String ) { 55 if ("".equals(val)) { 56 return new Integer (0); 57 } 58 return Integer.valueOf((String ) val); 59 } else if (val instanceof Character ) { 60 return new Integer (((Character ) val).charValue()); 61 } else if (val instanceof Boolean ) { 62 throw new Exception ("Boolean->Integer coercion exception"); 63 } else if (val instanceof Number ) { 64 return new Integer (((Number ) val).intValue()); 65 } 66 67 throw new Exception ("Integer coercion exception"); 68 } 69 70 77 public static Long coerceLong(Object val) 78 throws Exception { 79 if (val == null) { 80 return new Long (0); 81 } else if (val instanceof String ) { 82 if ("".equals(val)) { 83 return new Long (0); 84 } 85 return Long.valueOf((String ) val); 86 } else if (val instanceof Character ) { 87 return new Long (((Character ) val).charValue()); 88 } else if (val instanceof Boolean ) { 89 throw new Exception ("Boolean->Long coercion exception"); 90 } else if (val instanceof Number ) { 91 return new Long (((Number ) val).longValue()); 92 } 93 94 throw new Exception ("Long coercion exception"); 95 } 96 97 104 public static Double coerceDouble(Object val) 105 throws Exception { 106 if (val == null) { 107 return new Double (0); 108 } else if (val instanceof String ) { 109 if ("".equals(val)) { 110 return new Double (0); 111 } 112 113 117 118 return new Double ((String ) val); 119 } else if (val instanceof Character ) { 120 int i = ((Character ) val).charValue(); 121 122 return new Double (Double.parseDouble(String.valueOf(i))); 123 } else if (val instanceof Boolean ) { 124 throw new Exception ("Boolean->Double coercion exception"); 125 } else if (val instanceof Double ) { 126 return (Double ) val; 127 } else if (val instanceof Number ) { 128 return new Double (Double.parseDouble(String.valueOf(val))); 131 } 132 133 throw new Exception ("Double coercion exception"); 134 } 135 136 142 public static boolean isFloatingPoint(final Object o) { 143 return o instanceof Float || o instanceof Double ; 144 } 145 146 152 public static boolean isNumberable(final Object o) { 153 return o instanceof Integer 154 || o instanceof Long 155 || o instanceof Byte 156 || o instanceof Short 157 || o instanceof Character ; 158 } 159 160 } 161 | Popular Tags |