001 /*****************************************************************************
002 * Copyright (C) NanoContainer Organization. All rights reserved. *
003 * ------------------------------------------------------------------------- *
004 * The software in this package is published under the terms of the BSD *
005 * style license a copy of which has been included with this distribution in *
006 * the LICENSE.txt file. *
007 * *
008 * Original code by Joe Walnes *
009 *****************************************************************************/
010
011
012 package org.nanocontainer.reflection;
013
014 import java.util.HashMap;
015 import java.util.Map;
016
017 public class StringToObjectConverter {
018
019 private final Map converters = new HashMap();
020
021 public StringToObjectConverter() {
022 register(String.class, new Converter() {
023 public Object convert(String in) {
024 return in;
025 }
026 });
027
028 register(Integer.class, new Converter() {
029 public Object convert(String in) {
030 return in == null ? new Integer(0) : Integer.valueOf(in);
031 }
032 });
033
034 register(Long.class, new Converter() {
035 public Object convert(String in) {
036 return in == null ? new Long(0) : Long.valueOf(in);
037 }
038 });
039
040 register(Boolean.class, new Converter() {
041 public Object convert(String in) {
042 if (in == null || in.length() == 0) {
043 return Boolean.FALSE;
044 }
045 char c = in.toLowerCase().charAt(0);
046 return c == '1' || c == 'y' || c == 't' ? Boolean.TRUE : Boolean.FALSE;
047 }
048 });
049 }
050
051 public Object convertTo(Class desiredClass, String inputString) {
052 Converter converter = (Converter) converters.get(desiredClass);
053 if (converter == null) {
054 throw new InvalidConversionException("Cannot convert to type " + desiredClass.getName());
055 }
056 return converter.convert(inputString);
057 }
058
059 public void register(Class type, Converter converter) {
060 converters.put(type, converter);
061 }
062 }