Sunday, 30 November 2008

Property Management in Java (-D option)

System.getProperty is a static method on the System class that takes a (String) key and returns a (String) value. Standard system properties include java.home (where Java is installed) and java.class.path (the Java classpath) and os.name and os.version.

System properties are set on startup using the -D<key>=<value> option. These properties may need to be set in a launch script to a Java program.

Properties can also be maintained in an external file. Then you call System.getProperties to get a reference to the Properties object (that inherits from Hashtable). The Hashtable methods put and putall can be called on the object but their use is strongly discouraged in favour of the method setProperty which allows you to set String keys and values (i.e. it enforces a type-constraint on the keys of the Properties object).

Properties can be maintained in an external file and then setProperty can be used to add them to the application's properties table. Some people like to write singleton managers for properties so access can be centralised and controlled (and type-constraints enforced) for System properties.

No comments: