01: package org.depunit;
02:
03: import java.lang.reflect.*;
04: import java.util.*;
05:
06: public class BeanUtil {
07: public static void initializeClass(Class klass,
08: Map<String, ? extends Object> dataSet, Object instance)
09: throws InitializationException {
10: Method me = null;
11: try {
12: Method[] methods = klass.getMethods();
13: Map<String, Method> methodMap = new HashMap();
14:
15: for (Method m : methods)
16: methodMap.put(m.getName().toLowerCase(), m);
17:
18: Set<String> paramNames = dataSet.keySet();
19: for (String param : paramNames) {
20: me = methodMap.get("set" + param.toLowerCase());
21: if (me == null)
22: throw new InitializationException(
23: "Unable to locate method on "
24: + klass.getName()
25: + " to set param " + param);
26: //System.out.println("Calling "+m.getName()+" with param "+dataSet.get(param)+" on class "+m_classInstance);
27:
28: if (dataSet.get(param) instanceof String) {
29: Class type = me.getParameterTypes()[0]; //This assumes a lot
30: if (type == String.class)
31: me.invoke(instance, dataSet.get(param));
32: else if (type == int.class)
33: me.invoke(instance, new Integer(
34: (String) dataSet.get(param)));
35: else if (type == boolean.class)
36: me.invoke(instance, new Boolean(
37: (String) dataSet.get(param)));
38: else
39: System.out.println("Param type = " + type);
40: } else
41: me.invoke(instance, dataSet.get(param));
42: }
43: } catch (IllegalAccessException iae) {
44: throw new InitializationException(iae);
45: } catch (InvocationTargetException ite) {
46: //throw new InitializationException("Error invoking "+me.getName()+" on "+klass.getName());
47: throw new InitializationException(ite.getCause());
48: }
49: }
50: }
|