Commons Convert

Convert is a library dedicated to the task of converting an object of one type to another. The library is ideal for scripting languages or any application that needs to convert (or coerce) one Java object type to another.

Goals

  • Provide a simple API for converting one arbitrary Java object into another
  • Provide a comprehensive library of converters
  • Support locale-sensitive conversions for internationalization
  • Accommodate the conversion of application-defined types

Status

  • This code is in the commons sandbox
  • The code is unreleased
  • The API can be considered stable
  • The library needs unit tests
  • If you like the code and want to push it toward a release, then please join the mailing list!

Getting Started

Most Java applications will require data type conversion, and typically those conversions are hard-coded in the application on an as-needed basis. As an application grows, so do the number of hard-coded conversions. In time, you end up with duplicate code or duplicate conversions that behave differently depending on where they appear in code. Things get worse in enterprise-class applications where data is being exchanged between dissimilar systems and data type conversion gets really complicated.

A better approach would be to start off with a conversion library like Commons Convert that will accommodate the handful of conversions required by a small application, as well as the complicated, difficult-to-foresee conversions required by an enterprise-class application. The easiest and most scalable way to set up conversions is to create a facade or adapter:

public static Object convertTo(Object sourceObject, Class<?> targetClass) throws ClassNotFoundException, ConversionException {
    Converter<Object, Object> converter = Converters.getConverter(sourceObject.getClass(), targetClass);
    return converter.convert(sourceObject);
}


The application delegates all conversions to the static method.

Some conversions require a locale and/or time zone. The facade can be improved to accommodate localized conversions:

public static Object convertTo(Object sourceObject, Class<?> targetClass, Locale locale, TimeZone timezone) throws ClassNotFoundException, ConversionException {
    Converter<Object, Object> converter = Converters.getConverter(sourceObject.getClass(), targetClass);
    if (converter instanceof LocalizedConverter) {
        LocalizedConverter<Object, Object> localizedConverter = (LocalizedConverter) converter;
        return localizedConverter.convert(sourceObject, locale, timeZone);
    } else {
        return converter.convert(sourceObject);
    }
}

Documentation

Releases

None. This is a sandbox component.