|
37 | 37 | import org.springframework.format.Parser;
|
38 | 38 | import org.springframework.format.Printer;
|
39 | 39 | import org.springframework.lang.Nullable;
|
| 40 | +import org.springframework.util.Assert; |
| 41 | +import org.springframework.util.ClassUtils; |
40 | 42 | import org.springframework.util.StringUtils;
|
41 | 43 | import org.springframework.util.StringValueResolver;
|
42 | 44 |
|
@@ -65,6 +67,18 @@ public void setEmbeddedValueResolver(StringValueResolver resolver) {
|
65 | 67 | }
|
66 | 68 |
|
67 | 69 |
|
| 70 | + @Override |
| 71 | + public void addPrinter(Printer<?> printer) { |
| 72 | + Class<?> fieldType = getFieldType(printer, Printer.class); |
| 73 | + addConverter(new PrinterConverter(fieldType, printer, this)); |
| 74 | + } |
| 75 | + |
| 76 | + @Override |
| 77 | + public void addParser(Parser<?> parser) { |
| 78 | + Class<?> fieldType = getFieldType(parser, Parser.class); |
| 79 | + addConverter(new ParserConverter(fieldType, parser, this)); |
| 80 | + } |
| 81 | + |
68 | 82 | @Override
|
69 | 83 | public void addFormatter(Formatter<?> formatter) {
|
70 | 84 | addFormatterForFieldType(getFieldType(formatter), formatter);
|
@@ -97,15 +111,18 @@ public void addFormatterForFieldAnnotation(AnnotationFormatterFactory<? extends
|
97 | 111 |
|
98 | 112 |
|
99 | 113 | static Class<?> getFieldType(Formatter<?> formatter) {
|
100 |
| - Class<?> fieldType = GenericTypeResolver.resolveTypeArgument(formatter.getClass(), Formatter.class); |
101 |
| - if (fieldType == null && formatter instanceof DecoratingProxy) { |
| 114 | + return getFieldType(formatter, Formatter.class); |
| 115 | + } |
| 116 | + |
| 117 | + private static <T> Class<?> getFieldType(T instance, Class<T> genericInterface) { |
| 118 | + Class<?> fieldType = GenericTypeResolver.resolveTypeArgument(instance.getClass(), genericInterface); |
| 119 | + if (fieldType == null && instance instanceof DecoratingProxy) { |
102 | 120 | fieldType = GenericTypeResolver.resolveTypeArgument(
|
103 |
| - ((DecoratingProxy) formatter).getDecoratedClass(), Formatter.class); |
104 |
| - } |
105 |
| - if (fieldType == null) { |
106 |
| - throw new IllegalArgumentException("Unable to extract the parameterized field type from Formatter [" + |
107 |
| - formatter.getClass().getName() + "]; does the class parameterize the <T> generic type?"); |
| 121 | + ((DecoratingProxy) instance).getDecoratedClass(), genericInterface); |
108 | 122 | }
|
| 123 | + Assert.notNull(fieldType, () -> "Unable to extract the parameterized field type from " + |
| 124 | + ClassUtils.getShortName(genericInterface) + " [" + instance.getClass().getName() + |
| 125 | + "]; does the class parameterize the <T> generic type?"); |
109 | 126 | return fieldType;
|
110 | 127 | }
|
111 | 128 |
|
|
0 commit comments