The Properties class allows you to store and retrieve static String property types from files. I wrote two classes that makes Properties “dynamic” (so that you can reference the values of other keys) and parsable (so that instead of returning all String types, you can parse other supported types).
Dynamic Properties
Sometimes you may have a properties file with various keys that have the same value, but for flexibility purposes, you don’t want to share the same key because the value can change sometime in the future. At the same time, it can be cumbersome to duplicate larger values. Here’s a simple example:
backend.timeout: 5000 webservice.timeout: 5000 http.timeout: 30000 other.timeout: 30000
Here, you can see that two values are duplicated across four keys. With my DynamicProperties class, you can reference duplicate values like this:
default.short.timeout: 5000
default.long.timeout: 30000
backend.timeout: ${default.short.timeout}
webservice.timeout: ${default.short.timeout}
http.timeout: ${default.long.timeout}
other.timeout: ${default.long.timeout}
Parsable Properties
Every object returned from a properties file is a String type. If you represent other types of data in your properties file, chances are that you manually convert those values into other types. My ParsableProperties class extends DynamicProperties by adding support to automatically parse different types and lists. Using the above properties file, I can do this:
int backendTimeout = properties.getInteger("backend.timeout");
As opposed to the “old” way:
String backendTimeout = properties.getProperty("backend.timeout");
int converted = 0;
try {
converted = Integer.parseInt( backendTimeout );
} catch ( NumberFormatException e ) {
// Handle error
}
If you’re worried about losing the ability to handle the error, you can always provide a default value in the event that the value wasn’t parsable:
// Use a default value of 30000 ms if this property can't be found or parsed
int backendTimeout = properties.getInteger("backend.timeout", 30000);
Supported Types
The API supports all of the primitive wrappers (Boolean, Character, Double, Float, Integer, Long, Short), in addition to URI, URL, File, and Date. This class will also parse lists for all of the above types, so long as they are delimited by some token (the default token is the `~` char since a comma could potentially be used in number values).
- JAR files – for using in your project (41.8 KB)
- Source Code – includes source, JAR, and unit tests (106 KB)

One Trackback
[...] Contact « Dynamic and Parsable Properties [...]