forked from spring-projects/spring-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OptionalUnwrappingConverter.java
64 lines (48 loc) · 1.62 KB
/
OptionalUnwrappingConverter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package org.springframework.core.convert.support;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import java.util.*;
final class OptionalUnwrappingConverter implements ConditionalGenericConverter {
private final ConversionService conversionService;
public OptionalUnwrappingConverter(final ConversionService conversionService)
{
this.conversionService = conversionService;
}
@Override
public Set<ConvertiblePair> getConvertibleTypes()
{
return null;
}
@Override
public boolean matches(final TypeDescriptor sourceType, final TypeDescriptor targetType)
{
if (!Optional.class.isAssignableFrom(sourceType.getObjectType())) {
return false;
}
if (!sourceType.getResolvableType().hasGenerics()) {
return false;
}
return conversionService.canConvert(new GenericTypeDescriptor(sourceType), targetType);
}
@Override
public Object convert(final Object source, final TypeDescriptor sourceType, final TypeDescriptor targetType)
{
if (source == null) {
return null;
}
Optional<?> optionalSource = Optional.class.cast(source);
if (!optionalSource.isPresent()) {
return null;
}
return conversionService.convert(optionalSource.get(), new GenericTypeDescriptor(sourceType), targetType);
}
@SuppressWarnings("serial")
private static class GenericTypeDescriptor extends TypeDescriptor
{
GenericTypeDescriptor(final TypeDescriptor typeDescriptor)
{
super(typeDescriptor.getResolvableType().getGeneric(), null, typeDescriptor.getAnnotations());
}
}
}