package dk.thoerup.webconfig; import java.lang.reflect.Field; abstract public class ConfigLoader { // TODO: should this class be enhanced with a saveConfig() and a setValue() ?? public abstract String getValue(String paramName); public void loadConfig(Object configObject) { Field fields[] = configObject.getClass().getDeclaredFields(); for(Field field : fields) { field.setAccessible(true); ConfigVariable anno = field.getAnnotation(ConfigVariable.class); if (anno == null) continue; String value = getValue( field.getName() ); if (value == null) { //TODO: find another exception to throw here throw new RuntimeException("Could not find a value to this field: " + field.getName() ); } setFieldValue(field,configObject,value); } } public static void setFieldValue(Field field, Object configObject, String value) { field.setAccessible(true); try { if (field.getType().getName().equals("int") ) { field.setInt(configObject, Integer.parseInt(value) ); } else if (field.getType().getName().equals("boolean") ) { value = value.toLowerCase(); if (! (value.equals("true") || value.equals("false"))) { //TODO: Find another exception to throw here throw new RuntimeException("Only 'true' or 'false' as values for boolean field"); } field.setBoolean(configObject, Boolean.parseBoolean(value) ); } else if (field.getType().getName().equals("long") ) { field.setLong(configObject, Long.parseLong(value) ); } else if (field.getType().getName().equals("short") ) { field.setShort(configObject, Short.parseShort(value) ); } else if (field.getType().getName().equals("double") ) { field.setDouble(configObject, Double.parseDouble(value) ); } else if (field.getType().getName().equals("float") ) { field.setFloat(configObject, Float.parseFloat(value) ); } else if (field.getType().getName().equals("char") ) { field.setFloat(configObject, value.charAt(0) ); } else { field.set(configObject, value ); } } catch (IllegalAccessException e) { //this should never happen since we already have called setAccessible(true) throw new RuntimeException("How did we get here?", e); } } }