|
|
|||||
Evan Summers's BlogSystem PropertiesPosted by evanx on March 01, 2007 at 07:25 AM | Comments (0)
Let's use reflection to set a bunch of configurable values via the command-line using "system properties."
We put our configurable properties into a separate object, specifying the default values, as follows.
public class CommandoDemoProperties { public String host = "aptframework.net"; public int port = 80; public int sslPort = 443; public boolean useSSL = true; public String clientKeyStoreFileName = "keystores/client.private"; public String serverKeyStoreFileName = "keystores/server.public"; ... } We create the following helper to inject any command-line parameters via reflection, according to the field names, eg. -Dport=8080.
public class QSystemPropertyHelper { ... protected void injectSystemProperties(Object properties) throws IllegalAccessException { for (Field field : properties.getClass().getFields()) { Class type = field.getType(); String key = field.getName(); Object defaultValue = field.get(properties); Object value = defaultValue; String string = System.getProperty(key); if (string == null) continue; if (type == String.class) { value = string; } else if (type == Integer.class || type == int.class) { value = Integer.getInteger(key); } else if (type == Boolean.class || type == boolean.class) { value = Boolean.getBoolean(key); } else { logger.warning(key, type); } if (value != defaultValue) { field.set(properties, value); } } } } where we support properties which are strings, integers or boolean values.
Bookmark blog post: CommentsComments are listed in date ascending order (oldest first) | Post Comment | |||||
|
|