S
- The source typeT
- The target type@Indexed(value=TypeConverter.class) public interface TypeConverter<S,T>
A type converter for converting from one type to another.
Implementations should be stateless, simple and thread safe. Type converters are often best defined as Java lambdas. You should NOT perform any overly complex, blocking or slow conversions in implementations of this interface.
If dependency injection is required, carefully consider what you inject. Databases and I/O bound interfaces are not good candidates. In addition, injecting dependencies that may trigger the evaluation of beans that depend on configuration will cause problems because all type converters have not been registered yet.
Modifier and Type | Method and Description |
---|---|
default java.util.Optional<T> |
convert(S object,
java.lang.Class<T> targetType)
Converts from the given source object type to the target type.
|
java.util.Optional<T> |
convert(S object,
java.lang.Class<T> targetType,
ConversionContext context)
Converts from the given source object type to the target type.
|
static <ST,TT> TypeConverter<ST,TT> |
of(java.lang.Class<ST> sourceType,
java.lang.Class<TT> targetType,
java.util.function.Function<ST,TT> converter)
Creates a new
TypeConverter for the give source type, target type and conversion function. |
default java.util.Optional<T> convert(S object, java.lang.Class<T> targetType)
object
- The object typetargetType
- The target type being converted tojava.util.Optional<T> convert(S object, java.lang.Class<T> targetType, ConversionContext context)
Optional.empty()
in case the object is not convertible by catching any necessary exceptions and failing gracefully.object
- The object typetargetType
- The target type being converted tocontext
- The ConversionContext
static <ST,TT> TypeConverter<ST,TT> of(java.lang.Class<ST> sourceType, java.lang.Class<TT> targetType, java.util.function.Function<ST,TT> converter)
TypeConverter
for the give source type, target type and conversion function.ST
- The source generic typeTT
- The target generic typesourceType
- The source typetargetType
- The target typeconverter
- The converter function