1 10 11 12 package org.nanocontainer.reflection; 13 14 import java.util.HashMap ; 15 import java.util.Map ; 16 17 public class StringToObjectConverter { 18 19 private final Map converters = new HashMap (); 20 21 public StringToObjectConverter() { 22 register(String .class, new Converter() { 23 public Object convert(String in) { 24 return in; 25 } 26 }); 27 28 register(Integer .class, new Converter() { 29 public Object convert(String in) { 30 return in == null ? new Integer (0) : Integer.valueOf(in); 31 } 32 }); 33 34 register(Long .class, new Converter() { 35 public Object convert(String in) { 36 return in == null ? new Long (0) : Long.valueOf(in); 37 } 38 }); 39 40 register(Boolean .class, new Converter() { 41 public Object convert(String in) { 42 if (in == null || in.length() == 0) { 43 return Boolean.FALSE; 44 } 45 char c = in.toLowerCase().charAt(0); 46 return c == '1' || c == 'y' || c == 't' ? Boolean.TRUE : Boolean.FALSE; 47 } 48 }); 49 } 50 51 public Object convertTo(Class desiredClass, String inputString) { 52 Converter converter = (Converter) converters.get(desiredClass); 53 if (converter == null) { 54 throw new InvalidConversionException("Cannot convert to type " + desiredClass.getName()); 55 } 56 return converter.convert(inputString); 57 } 58 59 public void register(Class type, Converter converter) { 60 converters.put(type, converter); 61 } 62 } 63 | Popular Tags |