KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > nanocontainer > reflection > StringToObjectConverter


1 /*****************************************************************************
2  * Copyright (C) NanoContainer Organization. All rights reserved. *
3  * ------------------------------------------------------------------------- *
4  * The software in this package is published under the terms of the BSD *
5  * style license a copy of which has been included with this distribution in *
6  * the LICENSE.txt file. *
7  * *
8  * Original code by Joe Walnes *
9  *****************************************************************************/

10
11
12 package org.nanocontainer.reflection;
13
14 import java.util.HashMap JavaDoc;
15 import java.util.Map JavaDoc;
16
17 public class StringToObjectConverter {
18
19     private final Map JavaDoc converters = new HashMap JavaDoc();
20
21     public StringToObjectConverter() {
22         register(String JavaDoc.class, new Converter() {
23             public Object JavaDoc convert(String JavaDoc in) {
24                 return in;
25             }
26         });
27
28         register(Integer JavaDoc.class, new Converter() {
29             public Object JavaDoc convert(String JavaDoc in) {
30                 return in == null ? new Integer JavaDoc(0) : Integer.valueOf(in);
31             }
32         });
33
34         register(Long JavaDoc.class, new Converter() {
35             public Object JavaDoc convert(String JavaDoc in) {
36                 return in == null ? new Long JavaDoc(0) : Long.valueOf(in);
37             }
38         });
39
40         register(Boolean JavaDoc.class, new Converter() {
41             public Object JavaDoc convert(String JavaDoc 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 JavaDoc convertTo(Class JavaDoc desiredClass, String JavaDoc 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 JavaDoc type, Converter converter) {
60         converters.put(type, converter);
61     }
62 }
63
Popular Tags