1 19 20 21 package org.apache.cayenne.util; 22 23 import java.math.BigDecimal ; 24 import java.math.BigInteger ; 25 26 import org.apache.cayenne.exp.ExpressionException; 27 28 34 public final class ConversionUtil { 35 36 public static int toInt(Object object, int defaultValue) { 37 if (object == null) { 38 return defaultValue; 39 } 40 else if (object instanceof Number ) { 41 return ((Number ) object).intValue(); 42 } 43 else if (object instanceof String ) { 44 try { 45 return Integer.parseInt((String ) object); 46 } 47 catch (NumberFormatException ex) { 48 return defaultValue; 49 } 50 } 51 52 return defaultValue; 53 } 54 55 public static boolean toBoolean(Object object) { 56 if (object instanceof Boolean ) { 57 return ((Boolean ) object).booleanValue(); 58 } 59 60 if (object instanceof Number ) { 61 return ((Number ) object).intValue() != 0; 62 } 63 64 return object != null; 65 } 66 67 public static BigDecimal toBigDecimal(Object object) { 68 69 if (object == null) { 70 return null; 71 } 72 else if (object instanceof BigDecimal ) { 73 return (BigDecimal ) object; 74 } 75 else if (object instanceof BigInteger ) { 76 return new BigDecimal ((BigInteger ) object); 77 } 78 else if (object instanceof Number ) { 79 return new BigDecimal (((Number ) object).doubleValue()); 80 } 81 82 throw new ExpressionException("Can't convert to BigDecimal: " + object); 83 } 84 85 88 public static Comparable toComparable(Object object) { 89 if (object == null) { 90 return null; 91 } 92 else if (object instanceof Comparable ) { 93 return (Comparable ) object; 94 } 95 else if (object instanceof StringBuffer ) { 96 return object.toString(); 97 } 98 else if (object instanceof char[]) { 99 return new String ((char[]) object); 100 } 101 else { 102 throw new ClassCastException ( 103 "Invalid Comparable class:" + object.getClass().getName()); 104 } 105 } 106 107 110 public static String toString(Object object) { 111 if (object == null) { 112 return null; 113 } 114 else if (object instanceof String ) { 115 return (String ) object; 116 } 117 else if (object instanceof StringBuffer ) { 118 return object.toString(); 119 } 120 else if (object instanceof char[]) { 121 return new String ((char[]) object); 122 } 123 else { 124 throw new ClassCastException ( 125 "Invalid class for String conversion:" + object.getClass().getName()); 126 } 127 } 128 129 132 public static Object toUpperCase(Object object) { 133 if ((object instanceof String ) || (object instanceof StringBuffer )) { 134 return object.toString().toUpperCase(); 135 } 136 else if (object instanceof char[]) { 137 return new String ((char[]) object).toUpperCase(); 138 } 139 else { 140 return object; 141 } 142 } 143 144 private ConversionUtil() { 145 } 146 } 147 | Popular Tags |