Writing Custom Converters
back to index
Writing custom converters that integrate in the framework is also very easy. Follow these steps:
- Create a converter class by implementing the
IConverter interface. This interface has a single convert() method that is provided a data value to convert and a set of possible target classes in order of decreasing preferences. The data value to convert is guaranteed to be non-null, don't waste time checking for that. Your converter class should be thread-safe and reentrant.
- Your converter can get any runtime operation parameters from the env parameter. In particular, you should use the env.getLocale() method to retrieve the Locale under which the user wants your annotation to operate in a particular invocation. This locale may change from invocation to invocation, and needs not necessarily be the default locale (Think, for example, of your annotation processing data coming from an HTTP Request : each request will have its own locale).
- You must register your converter with the
Converters class. Registration involves calling the registerConverter() method passing it a source class, a target class, and an instance of your converter class.
A useful starting point would be to look at the source code of some of the existing converters. One of the easiest is the
StringAssigner class, which converts anything to a String. This particular converter also converts the string representation of an enumerated value to its corresponding enum constant.