You need to access configuration parameters as typed objects. In
other words, you have configuration parameters that may be numbers or
lists of strings, and you want to access them as typed objects instead
of first retrieving them as String
objects from a Properties
object.
Use the PropertiesConfiguration
from Commons Configuration in the org.apache.commons.configuration
package. This
class loads a properties file and provides access to numbers, arrays,
and lists. The following properties file contains three properties:
speed
is a floating-point number,
names
is a comma-separated list of
strings, and correct
is a boolean
value:
speed=23.332 names=Bob,Gautam,Jarret,Stefan correct=false
This properties file is stored in test.properties
in the working directory of
an application, which needs access to all three properties as a float
, List
, and boolean
. The following code creates a PropertiesConfiguration
and accesses each
property:
import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.PropertiesConfiguration; Configuration config = new PropertiesConfiguration( "test.properties" ); float speed = config.getFloat("speed")); List names = config.getList("names")); boolean correct = config.getBoolean("correct");
Passing a String
to the
constructor of PropertiesConfiguration
will load
configuration properties from a file named test.properties
. Properties are then
referenced by the key of the property in the properties file. This
recipe demonstrates a modest improvement upon the existing Properties
class that ships with the J2SE. The
methods provided by the Configuration
interface enable you to retrieve properties with a specific type,
throwing a NumberFormatException
,
ClassCastException
, and NoSuchElementException
if there is a problem
finding or parsing a property value.
For a full list of the methods provided by the Configuration
interface, see the Commons Configuration JavaDoc at http://commons.apache.org/configuration/apidocs.