Over a million developers have joined DZone.

Typed Properties in Java

DZone 's Guide to

Typed Properties in Java

· Java Zone ·
Free Resource


In typical java applications, especially web applications, you will have some properties.
Often you will have several properties files for different environments.

There is often a lot of boiler plate code to go with this. 


//Often with problems with paths etc.
Properties properties = ClassLoader.getResource("app.properties");
int myint = 0;
try {
	myint = Integer.parseInt(properties.getProperty("myint"));
	if ((myint<22) && (myint>658)) {
		//should I use default value?
		//should I throw exception ?
		//throw new IllegalArgumentException("myint property is outside valid range [23-657]");
} catch (NumberFormatException e) {
	//Should we use default?
	//Should we just log the error?
	//Should we close application because of invalid property?
} catch (IllegalArgumentException e) {
	//Should we use default?
	//Should we just log the error?	
	//Should we close application because of invalid property?


We want to :
  • Have a clear one-line Property definition.
  • Load a Property as the type it was intended.
  • Have a simple way to initialize a collection of properties.


Using JHPropertiesTyped ( Link ) is defined by 3 steps:
  • Define your properties, with name, type, restrictions, description - typical in an interface.
  • Define your collection of properties using your already defined properties.
  • Define your PropertyIO.
    • This can include a PropertyValidationHandler, for invalid properties.
    • This can include a pre and post setup.
The definition would look like:
public interface MyPropertiesDef {
	public static final Property<Integer> MYINT = new Property<Integer>("myint",new IntegerPropertyType(23,657));
	public static final Property<Locale> MYLOCALE = new Property<Locale>("mylocale", new LocalePropertyType());
	public static final Property<MyColors> MYCOLORS = new Property<MyColors>("mycolor",new EnumPropertyType(MyColors.class));

The class would be like:

public class MyProperties extends PropertyStaticCollection implements MyPropertiesDef {

	private static MyProperties instance=null;
	public MyProperties() {
		//Per default a collection has a "new LoggingPropertyValidationHandler(false)" instance.
		super(new ResourceFilePropertyIO("app.properties"),new LoggingPropertyValidationHandler(true));
	public MyProperties getInstance() {
		//Call this method at startup to initialize the properties
		if (instance==null) {
			instance = new MyProperties();
		return instance;
	public void preValidation() {
	public void postValidation() throws PropertyException {

The "PropertyValidationHandler" performs an action when one or more properties are invalid. This can be logging a message, sending a message, stopping application. It is easy to implement your own PropertyValidationHandler.

In a collection there are two methods you can choose to override. 

  • preValidation: Usually to set global parameters if needed.
  • postValidation: Usually to check Property dependencies, using the ActivationValidator class. Example: That some properties must be well defined if a certain property is well defined.
A Property is defined as:
  • Property<Type> NAME = Property<Type>(String name,PropertyType<Type> type,boolean nullAllowed,boolean readonly,String description);
    • nullAllowed: is optional; default is false.
    • readonly: is optional; default is false.
    • description: is optional; default is null.

Accessing Data

Once the collection is initialized, you can access the values. You know they are valid, otherwise the PropertyValidationHandler should have taken care of it. Either way, if there is a property which is not valid, null is returned, so you will soon know. But there is a quick way to set up a unit test that will test all your different environment properties. (Read more below) 
Integer v1 = MyPropertiesDef.MYINT.getTypedValue();
Locale v2 = MyPropertiesDef.MYLOCALE.getTypedValue();
MyColors v3 = MyPropertiesDef.MYCOLORS.getTypedValue();

You can also set a value both using the typed value or the string equivalent. A value will NOT be set if the PropertyType deems it invalid. 


You can access the methods on the collection. 

//For reloading

//For getting backup

//Getting property validation list
List<PropertyValidationDTO> list = MyProperties.getInstance().validation();

//Last saved
Date lastSaved = MyProperties.getInstance().getIo().getLastSaved();

Types Available

There are currently 39 distinct PropertyTypes : 

  • BooleanPropertyType
  • ByteSizePropertyType
  • CharsetPropertyType
  • ClassnamePropertyType
  • ColorPropertyType
  • DateFormatPropertyType
  • DateTimePropertyType
  • DecimalFormatPropertyType
  • DirectoryPropertyType
  • DoublePropertyType
  • EmailPropertyType
  • EnumPropertyType
  • EnvironmentPropertyType
  • FilenameFilterPropertyType
  • FilePropertyType
  • FileStructurePropertyType
  • HourIntervalsPropertyType
  • InetAddressPropertyType
  • IntegerPropertyType
  • IP4AddressPropertyType
  • LdapNamePropertyType
  • ListKeyValuePropertyType
  • ListPropertyType
  • LocalePropertyType
  • LongPropertyType
  • MonthPropertyType
  • PasswordPropertyType - Currently with AES, MD5 or SHA512 methods.
  • RegularExpressionPropertyType
  • SequencePropertyType
  • StringPropertiesPropertyType
  • StringPropertyType
  • TimeUnitPropertyType
  • TimeZonePropertyType
  • URIPropertyType
  • URLPropertyType
  • VersionPropertyType
  • WeekdayPropertyType

There are currently 16 distinct PropertyIO: 

  • AbstractPropertyIO
  • AbstractJDBCPropertyIO
  • AbstractXMLFilePropertyIO
  • AbstractXMLInputStreamPropertyIO
  • DatasourceJDBCPropertyIO
  • FilePropertyIO
  • InputStreamPropertyIO
  • JBossSystemPropertiesPropertyIO
  • MemoryPropertyIO
  • ResourceFilePropertyIO
  • ServletContextPropertyIO
  • UrlJDBCPropertyIO
  • WebContextParamsPropertyIO
  • CompositePropertyIO

It is easy to make your own PropertyType and PropertyIO.
It is easy to test all your different environment properties. (Read more below)

Unit Testing

Likely you have one or more properties for different environments. To test them all:

public class EnvironmentPropertyDataTest {	
	public void testAllEnvironmentProperties() {
		File[] files = FilePropertyIOFactory.findPropertyFiles(new File("/config/environments"),"myapp.properties");		
		for (File file : files) {			
			MockTestCollection collection = new MockTestCollection(file);
			try {
			} catch (PropertyException e) {				
				fail("Property file ["+file.getAbsolutePath()+"] failed with message:"+e.getMessage());				
	public void after() {
	class MockTestCollection extends PropertyStaticCollection implements MyPropertiesDef {
		public MockTestCollection(File file) {
			super(new FilePropertyIO(file));

Generation of Definitions

You can easily generate definitions for your existing properties. There are two ways: 

  • Using the main class in PropertiesJavaDefinitionPrinter.
  • Deploy "JHPropertiesTypedWebDemo" and go to the generate page.
Example of generation where input is:
Resulting in this:
//Value=[RED] - Suggesting type Color.
public final static Property<Color> MY_COLOR = new Property<Color>("my.color",new ColorPropertyType());

//Value=[email@email.com] - Suggesting type String.
public final static Property<String> MY_EMAIL = new Property<String>("my.email",new EmailPropertyType());

//Value=[123445] - Suggesting type Integer.
public final static Property<Integer> MY_INT = new Property<Integer>("my.int",new IntegerPropertyType());

//Value=[PI;E;COS;SIN] - Suggesting type List of String.
public final static Property<List<String>> MY_LIST = new Property<List<String>>("my.list",new ListPropertyType<String>(new StringPropertyType(),";"));


There are 3 libraries I have released currently in version 1.5:

  • JHPropertiesTyped-<version>.jar
    • The main framework at around 200 kb size.
    • The only dependency is Java JDK 1.6, Apache Commons Logging, and Java Servlet API (If you use classes dependent of this API)
  • JHPropertiesTypedWeb-<version>.jar
    • Renderers for all ProepertyTypes, an abstract version.
    • Dependencies is Java JDK 1.6, Apache Commons Logging, and Java Servlet API 
  • JHPropertiesTypedWebDemo-<version>.war
    • A demo of all PropertyTypes, read-only and writeable, generation page.
    • Dependencies is Java JDK 1.6, Apache Commons Logging, and Java Servlet API 
There is a fourth library in the pipeline, where there are no dependency restrictions. But this is not yet released; it depends on user feedback.

Web Enabling

The library JHPropertiesTypedWeb-<version>.jar is a renderer implementation of all the PropertyTypes, both for a read-only and a writeable implementation. It is very easy to integrate this in your own web app. Your only need to write 3 style sheet tags, and provide two pictures.

Final Comments and Links

The framework has complete javadoc and extensive documentation. Currently the test coverage is at around 75%. You can find the framework here:

Full Disclosure

I'm the developer of JHPropertiesTyped. I'm writing this article because I'm proud of my work and I think that many others will find this useful. The software is open sourced and is free under LGPLv3 License. 


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}