Apache Camel automatic type conversion

Apache Camel has good support for type conversion and it is easy to add your own type converters. In this blog post I’ll show how to create a generic type converter using reflection.

Type conversion is done by Camel either when you explicitly tell Camel to perform conversion or in some cases where Camel detects that a type conversion is needed. For example in this case Camel tries to perform type conversion from SourceType to TargetType:

This will fail since there is no type converter registered to handle conversion to TargetType. What if TargetType has a constructor taking a SourceType:

But this will also fail! My solution is to add a FallbackConverter that can handle this scenario, that is the target type having a single argument constructor taking the source type. The code looks like this:

A couple of things to notice:

  • The class has the @Converter annotation
  • The method has the @FallbackConverter
  • The signature of the method

You also need to include file META-INF/services/org/apache/camel/TypeConverter in your classpath that contains the package name. This allows Camel to automatically discover the type converter class.

Here is an integration test showing this example. I have also implemented a type converter that checks if the source type has a no argument method returning the target type. The source code for both type converters are available at GitHub.

Notice that this is just a demo of the capabilities of fallback converters. You have to decide if this approach is appropriate in your project. It might not be desirable to have a direct dependency between the TargetType and the SourceType. The overhead of reflection might be too high or it might have unintended consequences. For example the UsingMethod converter has the unintended consequence of finding and using the toString() method when a conversion to String is needed. The UsingConstructor is probably faster and safer since there are usually fewer constructors than public methods.

See the Camel documentation for type converts for more information.

Leave a Reply

Close Menu