1 7 package com.inversoft.util.typeconverter.converters; 8 9 10 import com.inversoft.util.StringTools; 11 import com.inversoft.util.typeconverter.BaseTypeConverter; 12 import com.inversoft.util.typeconverter.TypeConversionException; 13 14 15 27 public class NumberTypeConverter extends BaseTypeConverter { 28 29 44 public Object convertString(String value, Class convertTo) throws TypeConversionException { 45 46 boolean emptyNull = StringTools.isTrimmedEmpty(value); 48 if (emptyNull && !convertTo.isPrimitive()) { 49 return null; 50 } else if (value != null) { 51 value = value.trim(); 52 } 53 54 if (convertTo.isArray()) { 57 return super.convertStringToArray(value, null, convertTo); 58 } 59 60 try { 62 if (convertTo == Byte .class || convertTo == Byte.TYPE) { 63 return (emptyNull) ? new Byte ((byte) 0) : Byte.valueOf(value); 64 } else if (convertTo == Short .class || convertTo == Short.TYPE) { 65 return (emptyNull) ? new Short ((short) 0) : Short.valueOf(value); 66 } else if (convertTo == Integer .class || convertTo == Integer.TYPE) { 67 return (emptyNull) ? new Integer (0) : Integer.valueOf(value); 68 } else if (convertTo == Long .class || convertTo == Long.TYPE) { 69 return (emptyNull) ? new Long (0l) : Long.valueOf(value); 70 } else if (convertTo == Float .class || convertTo == Float.TYPE) { 71 return (emptyNull) ? new Float (0.0f) : Float.valueOf(value); 72 } else if (convertTo == Double .class || convertTo == Double.TYPE) { 73 return (emptyNull) ? new Double (0.0): Double.valueOf(value); 74 } 75 } catch (Exception e) { 76 throw new TypeConversionException("Error converting to type: " + convertTo.getName(), e); 77 } 78 79 throw new TypeConversionException("Type: " + convertTo.getName() 80 + " not supported by the NumberTypeConverter"); 81 } 82 83 96 public Object convertArray(Object [] values, Class convertTo) throws TypeConversionException { 97 98 if ((values == null || values.length == 0) && convertTo.isPrimitive()) { 100 return convertString(null, convertTo); 101 } 102 103 return super.convertArray(values, convertTo); 104 } 105 } 106 | Popular Tags |