01: /**
02: * L2FProd.com Common Components 7.3 License.
03: *
04: * Copyright 2005-2007 L2FProd.com
05: *
06: * Licensed under the Apache License, Version 2.0 (the "License");
07: * you may not use this file except in compliance with the License.
08: * You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing, software
13: * distributed under the License is distributed on an "AS IS" BASIS,
14: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15: * See the License for the specific language governing permissions and
16: * limitations under the License.
17: */package com.l2fprod.common.util.converter;
18:
19: import java.util.HashMap;
20: import java.util.Map;
21:
22: /**
23: * ConverterRegistry. <br>
24: *
25: */
26: public class ConverterRegistry implements Converter {
27:
28: private static ConverterRegistry sharedInstance = new ConverterRegistry();
29:
30: private Map fromMap;
31:
32: public ConverterRegistry() {
33: fromMap = new HashMap();
34:
35: new BooleanConverter().register(this );
36: new AWTConverters().register(this );
37: new NumberConverters().register(this );
38: }
39:
40: public void addConverter(Class from, Class to, Converter converter) {
41: Map toMap = (Map) fromMap.get(from);
42: if (toMap == null) {
43: toMap = new HashMap();
44: fromMap.put(from, toMap);
45: }
46: toMap.put(to, converter);
47: }
48:
49: public Converter getConverter(Class from, Class to) {
50: Map toMap = (Map) fromMap.get(from);
51: if (toMap != null) {
52: return (Converter) toMap.get(to);
53: } else {
54: return null;
55: }
56: }
57:
58: public Object convert(Class targetType, Object value) {
59: if (value == null) {
60: return null;
61: }
62:
63: Converter converter = getConverter(value.getClass(), targetType);
64: if (converter == null) {
65: throw new IllegalArgumentException("No converter from "
66: + value.getClass() + " to " + targetType.getName());
67: } else {
68: return converter.convert(targetType, value);
69: }
70: }
71:
72: public static ConverterRegistry instance() {
73: return sharedInstance;
74: }
75:
76: }
|