1 56 57 package org.objectstyle.cayenne.util; 58 59 import java.math.BigDecimal ; 60 import java.math.BigInteger ; 61 62 import org.objectstyle.cayenne.exp.ExpressionException; 63 64 70 public final class ConversionUtil { 71 72 public static int toInt(Object object, int defaultValue) { 73 if (object == null) { 74 return defaultValue; 75 } 76 else if (object instanceof Number ) { 77 return ((Number ) object).intValue(); 78 } 79 else if (object instanceof String ) { 80 try { 81 return Integer.parseInt((String ) object); 82 } 83 catch (NumberFormatException ex) { 84 return defaultValue; 85 } 86 } 87 88 return defaultValue; 89 } 90 91 public static boolean toBoolean(Object object) { 92 if (object instanceof Boolean ) { 93 return ((Boolean ) object).booleanValue(); 94 } 95 96 if (object instanceof Number ) { 97 return ((Number ) object).intValue() != 0; 98 } 99 100 return object != null; 101 } 102 103 public static BigDecimal toBigDecimal(Object object) { 104 105 if (object == null) { 106 return null; 107 } 108 else if (object instanceof BigDecimal ) { 109 return (BigDecimal ) object; 110 } 111 else if (object instanceof BigInteger ) { 112 return new BigDecimal ((BigInteger ) object); 113 } 114 else if (object instanceof Number ) { 115 return new BigDecimal (((Number ) object).doubleValue()); 116 } 117 118 throw new ExpressionException("Can't convert to BigDecimal: " + object); 119 } 120 121 124 public static Comparable toComparable(Object object) { 125 if (object == null) { 126 return null; 127 } 128 else if (object instanceof Comparable ) { 129 return (Comparable ) object; 130 } 131 else if (object instanceof StringBuffer ) { 132 return object.toString(); 133 } 134 else if (object instanceof char[]) { 135 return new String ((char[]) object); 136 } 137 else { 138 throw new ClassCastException ( 139 "Invalid Comparable class:" + object.getClass().getName()); 140 } 141 } 142 143 146 public static String toString(Object object) { 147 if (object == null) { 148 return null; 149 } 150 else if (object instanceof String ) { 151 return (String ) object; 152 } 153 else if (object instanceof StringBuffer ) { 154 return object.toString(); 155 } 156 else if (object instanceof char[]) { 157 return new String ((char[]) object); 158 } 159 else { 160 throw new ClassCastException ( 161 "Invalid class for String conversion:" + object.getClass().getName()); 162 } 163 } 164 165 168 public static Object toUpperCase(Object object) { 169 if ((object instanceof String ) || (object instanceof StringBuffer )) { 170 return object.toString().toUpperCase(); 171 } 172 else if (object instanceof char[]) { 173 return new String ((char[]) object).toUpperCase(); 174 } 175 else { 176 return object; 177 } 178 } 179 180 private ConversionUtil() { 181 } 182 } 183 | Popular Tags |