01: /*
02: * Copyright Javelin Software, All rights reserved.
03: */
04:
05: package com.javelin.swinglets;
06:
07: import java.awt.*;
08: import java.util.*;
09: import java.io.*;
10: import java.lang.reflect.*;
11:
12: /**
13: * SComponentLoaded is used to load Beans from streams, or readers.
14: * <P>
15: * This assumes all property values are Strings.
16: *
17: * @author Robin Sharp
18: */
19:
20: public class SComponentLoader {
21: /**
22: * The first property in the stream must have the format<br>
23: * Class=class name<br>
24: * subsequent properties have the format<br>
25: * PropertyName=value<br>
26: */
27: public static Object loadProperties(InputStream inputStream)
28: throws InstantiationException {
29: try {
30: Properties properties = new Properties();
31: properties.load(inputStream);
32:
33: return loadProperties(properties);
34: } catch (Exception e) {
35: e.printStackTrace();
36: throw new InstantiationException(
37: "Cannot load class from stream.");
38: }
39: }
40:
41: /**
42: * The first property in the stream must have the format<br>
43: * Class=class name<br>
44: * subsequent properties have the format<br>
45: * PropertyName=value<br>
46: */
47: public static Object loadProperties(Properties properties)
48: throws InstantiationException {
49: try {
50: Object object = Class.forName(
51: properties.getProperty("Class")).newInstance();
52:
53: Method[] methods = object.getClass().getMethods();
54:
55: String key = null;
56: String value = null;
57:
58: for (Enumeration keys = properties.keys(); keys
59: .hasMoreElements();) {
60: key = (String) keys.nextElement();
61:
62: if ("Class".equals(key))
63: continue;
64:
65: value = properties.getProperty(key);
66:
67: invokeMethod(object, methods, key, value);
68: }
69:
70: return object;
71: } catch (Exception e) {
72: e.printStackTrace();
73: throw new InstantiationException(
74: "Cannot load class from properties.");
75: }
76: }
77:
78: /**
79: * Invoke the method with the value
80: */
81: protected static void invokeMethod(Object object, Method[] methods,
82: String method, String argument)
83: throws InvocationTargetException, IllegalAccessException {
84: String methodName = "set" + method;
85:
86: for (int index = 0; index < methods.length; index++) {
87:
88: if (methods[index].getName().equals(methodName)) {
89: methods[index]
90: .invoke(object, new Object[] { argument });
91: break;
92: }
93: }
94: }
95:
96: }
|