01: package org.andromda.core.common;
02:
03: import java.lang.reflect.Constructor;
04: import java.lang.reflect.Method;
05:
06: import java.util.HashMap;
07: import java.util.Map;
08:
09: /**
10: * A class used for converting simple types to other types (i.e.
11: * java.lang.String -> java.lang.Integer, etc).
12: *
13: * @author Chad Brandon
14: */
15: public class Converter {
16: /**
17: * The prefix of the 'valueOf' method available on wrapper classes.
18: */
19: private static final String VALUE_OF_METHOD_NAME = "valueOf";
20:
21: /**
22: * Attempts to convert the <code>object</code> to the <code>expectedType</code>.
23: *
24: * @param object the object to convert.
25: * @param expectedType the type to which it should be converted.
26: * @return the converted object
27: */
28: public static Object convert(Object object, Class expectedType) {
29: try {
30: if (expectedType == String.class) {
31: object = object.toString();
32: } else if (expectedType == Class.class) {
33: object = ClassUtils.loadClass(object.toString());
34: } else {
35: final Class originalType = expectedType;
36: if (expectedType.isPrimitive()) {
37: expectedType = (Class) primitiveWrappers
38: .get(expectedType);
39: }
40: Method method = null;
41: try {
42: method = expectedType.getDeclaredMethod(
43: VALUE_OF_METHOD_NAME, new Class[] { object
44: .getClass() });
45: object = method.invoke(expectedType,
46: new Object[] { object });
47: } catch (final NoSuchMethodException exception) {
48: // - ignore
49: }
50:
51: // - if we couldn't find the method try with the constructor
52: if (method == null) {
53: Constructor constructor;
54: try {
55: constructor = expectedType
56: .getConstructor(new Class[] { originalType });
57: object = constructor
58: .newInstance(new Object[] { object });
59: } catch (final NoSuchMethodException exception) {
60: throw new IntrospectorException(
61: "Could not convert '" + object
62: + "' to type '"
63: + expectedType.getName() + "'");
64: }
65: }
66: }
67: } catch (final Throwable throwable) {
68: throw new IntrospectorException(throwable);
69: }
70: return object;
71: }
72:
73: /**
74: * Stores each primitive and its associated wrapper class.
75: */
76: private static final Map primitiveWrappers = new HashMap();
77:
78: /**
79: * Initialize the primitiveWrappers.
80: */
81: static {
82: primitiveWrappers.put(boolean.class, Boolean.class);
83: primitiveWrappers.put(int.class, Integer.class);
84: primitiveWrappers.put(long.class, Long.class);
85: primitiveWrappers.put(short.class, Short.class);
86: primitiveWrappers.put(byte.class, Byte.class);
87: primitiveWrappers.put(float.class, Float.class);
88: primitiveWrappers.put(double.class, Double.class);
89: primitiveWrappers.put(char.class, Character.class);
90: }
91: }
|