/[projects]/WebConfig/src/dk/thoerup/webconfig/ConfigLoader.java
ViewVC logotype

Contents of /WebConfig/src/dk/thoerup/webconfig/ConfigLoader.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1339 - (show annotations) (download)
Wed Apr 20 15:19:32 2011 UTC (13 years, 2 months ago) by torben
File size: 2218 byte(s)
First iteration on config loader system
1 package dk.thoerup.webconfig;
2
3
4 import java.lang.reflect.Field;
5
6
7
8 abstract public class ConfigLoader {
9 // TODO: should this class be enhanced with a saveConfig() and a setValue() ??
10
11
12 public abstract String getValue(String paramName);
13
14 public void loadConfig(Object configObject) {
15
16 Field fields[] = configObject.getClass().getDeclaredFields();
17
18 for(Field field : fields) {
19 field.setAccessible(true);
20
21 ConfigVariable anno = field.getAnnotation(ConfigVariable.class);
22 if (anno == null)
23 continue;
24
25 String value = getValue( field.getName() );
26 if (value == null) {
27 //TODO: find another exception to throw here
28 throw new RuntimeException("Could not find a value to this field: " + field.getName() );
29 }
30
31 setFieldValue(field,configObject,value);
32 }
33
34 }
35
36 public static void setFieldValue(Field field, Object configObject, String value) {
37
38 field.setAccessible(true);
39 try {
40
41 if (field.getType().getName().equals("int") ) {
42 field.setInt(configObject, Integer.parseInt(value) );
43 } else if (field.getType().getName().equals("boolean") ) {
44 value = value.toLowerCase();
45 if (! (value.equals("true") || value.equals("false"))) {
46 //TODO: Find another exception to throw here
47 throw new RuntimeException("Only 'true' or 'false' as values for boolean field");
48 }
49 field.setBoolean(configObject, Boolean.parseBoolean(value) );
50 } else if (field.getType().getName().equals("long") ) {
51 field.setLong(configObject, Long.parseLong(value) );
52 } else if (field.getType().getName().equals("short") ) {
53 field.setShort(configObject, Short.parseShort(value) );
54 } else if (field.getType().getName().equals("double") ) {
55 field.setDouble(configObject, Double.parseDouble(value) );
56 } else if (field.getType().getName().equals("float") ) {
57 field.setFloat(configObject, Float.parseFloat(value) );
58 } else if (field.getType().getName().equals("char") ) {
59 field.setFloat(configObject, value.charAt(0) );
60 } else {
61 field.set(configObject, value );
62 }
63 } catch (IllegalAccessException e) {
64 //this should never happen since we already have called setAccessible(true)
65 throw new RuntimeException("How did we get here?", e);
66 }
67 }
68
69 }

  ViewVC Help
Powered by ViewVC 1.1.20