/** * Converts from the given source object type to the target type. * * @param object The object type * @param targetType The target type being converted to * @return The converted type or empty if the conversion is not possible */ default Optional<T> convert(S object, Class<T> targetType) { return convert(object, targetType, ConversionContext.DEFAULT); }
@SuppressWarnings("unchecked") @Override public <T> Optional<T> convert(Object object, Class<T> targetType, ConversionContext context) { if (object == null || targetType == null || context == null) { return Optional.empty(); } if (targetType == Object.class) { return Optional.of((T) object); } Class<?> sourceType = object.getClass(); targetType = ReflectionUtils.getWrapperType(targetType); if (targetType.isInstance(object) && !Iterable.class.isInstance(object) && !Map.class.isInstance(object)) { return Optional.of((T) object); } Optional<? extends Class<? extends Annotation>> formattingAnn = context.getAnnotationMetadata().getAnnotationTypeByStereotype(Format.class); Class<? extends Annotation> formattingAnnotation = formattingAnn.orElse(null); ConvertiblePair pair = new ConvertiblePair(sourceType, targetType, formattingAnnotation); TypeConverter typeConverter = converterCache.get(pair); if (typeConverter == null) { typeConverter = findTypeConverter(sourceType, targetType, formattingAnnotation); if (typeConverter == null) { return Optional.empty(); } else { converterCache.put(pair, typeConverter); } } return typeConverter.convert(object, targetType, context); }