spiralcraft.util.string auto-conversion mechanism

The spiralcraft.util.string package, in the spiralcraft-core module contains the StringConverter utility, which provides a facility to automatically convert between Java classes and canonical, default human readable and writable String representations.

The auto-conversion package is used by many other subsystems to provide a stable and reliable way to convert to and from String representations that are consumable by humans. The String representations provide flexibility for handling native Java types within the following interfaces:

  • Text based network protocols, including HTTP URL and form data.
  • Application data entered and viewed by users in textual form
  • Text based file formats such as XML and CSV
  • Configuration / Dependency Injection mechanisms which turn textual configuration data into Java types

By implementing a StringConverter and supplying it to the applicable components, the default auto-conversion behavior can be overridden for specific types.

The following types (and their primitive equivalents, where applicable) are automatically detected and handled:

  • java.lang.String
  • java.lang.Integer
  • java.lang.Boolean
  • java.lang.Float
  • java.lang.Long
  • java.lang.Double
  • java.lang.Short
  • java.lang.Byte
  • java.lang.Character
  • java.lang.Class (uses thread context ClassLoader)
  • java.math.BigInteger
  • java.math.BigDecimal
  • java.net.URI

A fallback handler automatically handles any Class with a constructor that accepts a single argument of type java.lang.String. The toString() method of the object should provide output that is compatible with this String constructor, or the conversion will fail when used bidirectionally. If this is not possible, provide your own StringConverter instance.

This means that adding a String constructor to your POJO is likely all that you need to do in order to have your POJO participate in this mechanism, and benefit from automatic conversion between UI elements and model data.

API example

 StringConverter converter = StringConverter.getInstance(Long.class);
 
 String timeString = converter.toString(System.currentTimeMillis());
 
 Date now = new Date(converter.fromString(timeString));