Sapphire Developer Guide > Services

UniversalConversionService

UniversalConversionService converts an object to the specified type. It is intended for cases where implementing a regular ConversionService is impossible or impractical.

For instance, to implement a string to an enum conversion using ConversionService, one would need to provide a separate implementation for each enum, which is not very practical. On the other hand, a single UniversalConversionService implementation can handle all string to enum conversions. UniversalConversionService can also be used to integrate Sapphire with a third-party library of conversions.

The cost of flexibility is performance. While every ConversionService implementation declares what conversion it can perform, the UniversalConversionService implementations are opaque. Sapphire must try each one in turn until a successful conversion is found.

For best performance, UniversalConversionService should only be used in cases where a ConversionService implementation is impossible or impractical.

Example

public class StringToEnumConversionService extends UniversalConversionService
{
    @Override
    public <T> T convert( Object object, Class<T> type )
    {
        T result = null;

        if( object instanceof String && Enum.class.isAssignableFrom( type ) )
        {
            ...
        }

        return result;
    }
}