...
We have most of the common converters for common Java types in the org.apache.camel.converter package and its children.
Discovering Fallback Type Converters
Available in Camel 2.0
The AnnotationTypeConverterLoader has been enhanced to also look for methods defined with a @FallbackConverter annotation, and register it as a fallback type converter.
Fallback type converters is used as a last resort of hopes for converting a given value to another type. Its used when the regular type converters give up.
The fallback converters is also meant for a broader scope so its method signature is a bit different:
Code Block |
---|
@FallbackConverter
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry)
|
The Exchange
parameter is optional, just as its with the regular @Converter
methods.
The purpose with this broad scope method signature is allowing you to control if you can convert the given type or not. The type
parameter holds the type we want the value
converted to. Its used internally in Camel for wrapper objects so we can delegate the type convertions to the body that is wrapped.
For instance in the method below we will handle all type conversions that is based on the wrapper class GenericFile
and we let Camel do the type conversions on its body instead.
Code Block |
---|
@FallbackConverter
public static <T> T convertTo(Class<T> type, Exchange exchange, Object value, TypeConverterRegistry registry) {
// use a fallback type converter so we can convert the embedded body if the value is GenericFile
if (GenericFile.class.isAssignableFrom(value.getClass())) {
GenericFile file = (GenericFile) value;
Class from = file.getBody().getClass();
TypeConverter tc = registry.lookup(type, from);
if (tc != null) {
Object body = file.getBody();
return tc.convertTo(type, exchange, body);
}
}
return null;
}
|
Writing your own Type Converters
...