/[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 1346 - (show annotations) (download)
Wed Apr 20 17:16:28 2011 UTC (13 years, 1 month ago) by torben
File size: 2316 byte(s)
Make it possible to differentiate between variable name and config-file property name
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 propertyName = anno.propertyname().equals("") ? field.getName() : anno.propertyname();
26
27 String value = getValue( propertyName );
28 if (value == null) {
29 //TODO: find another exception to throw here
30 throw new RuntimeException("Could not find a value to this field: " + field.getName() );
31 }
32
33 setFieldValue(field,configObject,value);
34 }
35
36 }
37
38 public static void setFieldValue(Field field, Object configObject, String value) {
39
40 field.setAccessible(true);
41 try {
42
43 if (field.getType().getName().equals("int") ) {
44 field.setInt(configObject, Integer.parseInt(value) );
45 } else if (field.getType().getName().equals("boolean") ) {
46 value = value.toLowerCase();
47 if (! (value.equals("true") || value.equals("false"))) {
48 //TODO: Find another exception to throw here
49 throw new RuntimeException("Only 'true' or 'false' as values for boolean field");
50 }
51 field.setBoolean(configObject, Boolean.parseBoolean(value) );
52 } else if (field.getType().getName().equals("long") ) {
53 field.setLong(configObject, Long.parseLong(value) );
54 } else if (field.getType().getName().equals("short") ) {
55 field.setShort(configObject, Short.parseShort(value) );
56 } else if (field.getType().getName().equals("double") ) {
57 field.setDouble(configObject, Double.parseDouble(value) );
58 } else if (field.getType().getName().equals("float") ) {
59 field.setFloat(configObject, Float.parseFloat(value) );
60 } else if (field.getType().getName().equals("char") ) {
61 field.setFloat(configObject, value.charAt(0) );
62 } else {
63 field.set(configObject, value );
64 }
65 } catch (IllegalAccessException e) {
66 //this should never happen since we already have called setAccessible(true)
67 throw new RuntimeException("How did we get here?", e);
68 }
69 }
70
71 }

  ViewVC Help
Powered by ViewVC 1.1.20