File tree 2 files changed +46
-0
lines changed
main/java/org/springframework/core/convert/converter
test/java/org/springframework/core/convert/converter
2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change 17
17
package org .springframework .core .convert .converter ;
18
18
19
19
import org .springframework .lang .Nullable ;
20
+ import org .springframework .util .Assert ;
20
21
21
22
/**
22
23
* A converter converts a source object of type {@code S} to a target of type {@code T}.
26
27
* <p>Implementations may additionally implement {@link ConditionalConverter}.
27
28
*
28
29
* @author Keith Donald
30
+ * @author Josh Cummings
29
31
* @since 3.0
30
32
* @param <S> the source type
31
33
* @param <T> the target type
@@ -42,4 +44,20 @@ public interface Converter<S, T> {
42
44
@ Nullable
43
45
T convert (S source );
44
46
47
+ /**
48
+ * Construct a composed {@link Converter} that first applies this {@link Converter} to
49
+ * its input, and then applies the {@code after} {@link Converter} to the result.
50
+ *
51
+ * @since 5.2
52
+ * @param <U> the type of output of both the {@code after} {@link Converter} and the
53
+ * composed {@link Converter}
54
+ * @param after the {@link Converter} to apply after this {@link Converter}
55
+ * is applied
56
+ * @return a composed {@link Converter} that first applies this {@link Converter} and then
57
+ * applies the {@code after} {@link Converter}
58
+ */
59
+ default <U > Converter <S , U > andThen (Converter <? super T , ? extends U > after ) {
60
+ Assert .notNull (after , "after cannot be null" );
61
+ return (S s ) -> after .convert (convert (s ));
62
+ }
45
63
}
Original file line number Diff line number Diff line change
1
+ package org .springframework .core .convert .converter ;
2
+
3
+ import org .junit .jupiter .api .Test ;
4
+
5
+ import static org .assertj .core .api .Assertions .assertThat ;
6
+ import static org .assertj .core .api .Assertions .assertThatExceptionOfType ;
7
+
8
+ /**
9
+ * Tests for {@link Converter}
10
+ *
11
+ * @author Josh Cummings
12
+ */
13
+ public class ConverterTests {
14
+ Converter <Integer , Integer > moduloTwo = number -> number % 2 ;
15
+
16
+ @ Test
17
+ public void andThenWhenGivenANullConverterThenThrowsException () {
18
+ assertThatExceptionOfType (IllegalArgumentException .class )
19
+ .isThrownBy (() -> this .moduloTwo .andThen (null ));
20
+ }
21
+
22
+ @ Test
23
+ public void andThenWhenGivenConverterThenComposesInOrder () {
24
+ Converter <Integer , Integer > addOne = number -> number + 1 ;
25
+ assertThat (this .moduloTwo .andThen (addOne ).convert (13 )).isEqualTo (2 );
26
+ assertThat (addOne .andThen (this .moduloTwo ).convert (13 )).isEqualTo (0 );
27
+ }
28
+ }
You can’t perform that action at this time.
0 commit comments