Package io.micronaut.core.convert
Interface TypeConverter<S,T>
- Type Parameters:
S
- The source typeT
- The target type
- All Known Subinterfaces:
FormattingTypeConverter<S,
T, A>
- All Known Implementing Classes:
CharSequenceToEnumConverter
,CorsOriginConverter
,MultiValuesConverterFactory.AbstractConverterToMultiValues
,MultiValuesConverterFactory.IterableToMultiValuesConverter
,MultiValuesConverterFactory.MapToMultiValuesConverter
,MultiValuesConverterFactory.MultiValuesToIterableConverter
,MultiValuesConverterFactory.MultiValuesToMapConverter
,MultiValuesConverterFactory.MultiValuesToObjectConverter
,MultiValuesConverterFactory.ObjectToMultiValuesConverter
,ReadableBytesTypeConverter
,SameSiteConverter
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.
- Since:
- 1.0
- Author:
- Graeme Rocher
-
Method Summary
Modifier and TypeMethodDescriptionConverts from the given source object type to the target type.convert
(S object, Class<T> targetType, ConversionContext context) Converts from the given source object type to the target type.static <ST,
TT> TypeConverter<ST, TT> Creates a newTypeConverter
for the give source type, target type and conversion function.
-
Method Details
-
convert
Converts from the given source object type to the target type.- Parameters:
object
- The object typetargetType
- The target type being converted to- Returns:
- The converted type or empty if the conversion is not possible
-
convert
Converts from the given source object type to the target type. Implementers should take care to returnOptional.empty()
in case the object is not convertible by catching any necessary exceptions and failing gracefully.- Parameters:
object
- The object typetargetType
- The target type being converted tocontext
- TheConversionContext
- Returns:
- The converted type or empty if the conversion is not possible
-
of
static <ST,TT> TypeConverter<ST,TT> of(Class<ST> sourceType, Class<TT> targetType, Function<ST, TT> converter) Creates a newTypeConverter
for the give source type, target type and conversion function.- Type Parameters:
ST
- The source generic typeTT
- The target generic type- Parameters:
sourceType
- The source typetargetType
- The target typeconverter
- The converter function- Returns:
- The converter instance
-