...
- static methods are encouraged to reduce caching; but instance methods are fine, particularly if you want to allow optional dependency injection to customize the converter
- converter methods should be thread safe and reentrant
Encoding support for byte[] and String Conversion
Available in Camel 1.5
Since Java provides converting the byte[] to String and String to byte[] with the charset name parameter. You can define the charset name by setting the exchange property name Exchange.CHARSET_NAME
with the charset name, such as "UTF-8"
or "iso-8859-1"
.
Exchange parameter
Available in Camel 1.5
The type converter accepts the Exchange
as an optional 2nd parameter. This is usable if the type converter for instance needs information from the current exchange. For instance combined with the encoding support its possible for type converters to convert with the configured encoding. An example from camel-core for the byte[] -> String
converter:
Code Block |
---|
@Converter public static String toString(byte[] data, Exchange exchange) { if (exchange != null) { String charsetName = (String) exchange.getProperty(Exchange.CHARSET_NAME); if (charsetName != null) { try { return new String(data, charsetName); } catch (UnsupportedEncodingException e) { LOG.warn("Can't convert the byte to String with the charset " + charsetName, e); } } } return new String(data); } |