1616
1717package org .springframework .kafka .support .serializer ;
1818
19- import java .util .LinkedHashMap ;
20- import java .util .Map ;
19+ import java .util .*;
2120import java .util .Map .Entry ;
2221
2322import org .apache .kafka .common .errors .SerializationException ;
3231 * @author Gary Russell
3332 * @author Artem Bilan
3433 * @author Wang Zhiyang
34+ * @author Mahesh Aravind V
3535 *
3636 * @since 2.7.9
3737 *
3838 */
3939public class DelegatingByTypeSerializer implements Serializer <Object > {
4040
41- private final Map <Class <?>, Serializer <?>> delegates = new LinkedHashMap <>();
41+ private static final Comparator <Class <?>> DELEGATES_ASSIGNABILITY_COMPARATOR =
42+ (type1 , type2 ) -> {
43+
44+ if (type1 .isAssignableFrom (type2 )) {
45+ return 1 ;
46+ }
47+ if (type2 .isAssignableFrom (type1 )) {
48+ return -1 ;
49+ }
50+
51+ return 0 ;
52+ };
53+
54+ private final Map <Class <?>, Serializer <?>> delegates = new TreeMap <>(DELEGATES_ASSIGNABILITY_COMPARATOR );
4255
4356 private final boolean assignable ;
4457
@@ -51,17 +64,23 @@ public DelegatingByTypeSerializer(Map<Class<?>, Serializer<?>> delegates) {
5164 }
5265
5366 /**
54- * Construct an instance with the map of delegates; keys matched exactly or if the
55- * target object is assignable to the key, depending on the assignable argument.
56- * If assignable, entries are checked in the natural entry order so an ordered map
57- * such as a {@link LinkedHashMap} is recommended.
58- * @param delegates the delegates.
59- * @param assignable whether the target is assignable to the key.
67+ * Construct an instance with the map of delegates.
68+ * If {@code assignable} is {@code false}, only exact key matches are considered.
69+ * If {@code assignable} is {@code true}, a delegate is selected if its key class
70+ * is assignable from the target object's class. When multiple matches are possible,
71+ * the most specific matching class is selected — that is, the closest match in the
72+ * class hierarchy.
73+ *
74+ * @param delegates the delegates
75+ * @param assignable true if {@link #findDelegate(Object, Map)} should consider assignability to
76+ * the key rather than an exact match.
77+ *
6078 * @since 2.8.3
6179 */
6280 public DelegatingByTypeSerializer (Map <Class <?>, Serializer <?>> delegates , boolean assignable ) {
6381 Assert .notNull (delegates , "'delegates' cannot be null" );
6482 Assert .noNullElements (delegates .values (), "Serializers in delegates map cannot be null" );
83+
6584 this .delegates .putAll (delegates );
6685 this .assignable = assignable ;
6786 }
@@ -99,7 +118,7 @@ public byte[] serialize(String topic, Headers headers, Object data) {
99118 return delegate .serialize (topic , headers , data );
100119 }
101120
102- private <T > Serializer <T > findDelegate (T data ) {
121+ protected <T > Serializer <T > findDelegate (T data ) {
103122 return findDelegate (data , this .delegates );
104123 }
105124
0 commit comments