@@ -744,29 +744,40 @@ public <K,V> Map<K,V> getMap(@NonNull final String key, @NonNull final Class<K>
744
744
});
745
745
}
746
746
747
-
748
747
@ SuppressWarnings ("unchecked" )
749
748
private <V , K > Map <K , V > constructValuesMap (@ NonNull String key , @ NonNull Class <K > keyClass ,
750
749
@ NonNull Class <V > valueClass , Object defaultValue ) {
751
- Map <K , V > value = get (key , Map .class );
752
- if (value == null ) {
750
+ Map <K , V > originalMap = get (key , Map .class );
751
+ if (originalMap == null ) {
753
752
return (Map <K , V >) defaultValue ;
754
753
}
755
- for (Map .Entry <K , V > entry : value .entrySet ()) {
756
- if (entry .getKey () != null && !keyClass .isAssignableFrom (entry .getKey ().getClass ())) {
757
- throw new ClassCastException (String .format ("Map key cannot be cast to %s" , keyClass .getName ()));
754
+ Map <K , V > result = new HashMap <>();
755
+ for (Map .Entry <K , V > entry : originalMap .entrySet ()) {
756
+ K originalKey = entry .getKey ();
757
+ V value = entry .getValue ();
758
+ K newKey = originalKey ;
759
+ // Convert key if necessary
760
+ if (originalKey != null && !keyClass .isAssignableFrom (originalKey .getClass ())) {
761
+ if (originalKey instanceof Number && NUMBER_CONVERTERS .containsKey (keyClass )) {
762
+ Function <Number , ?> converter = NUMBER_CONVERTERS .get (keyClass );
763
+ newKey = (K ) converter .apply ((Number ) originalKey );
764
+ } else {
765
+ throw new ClassCastException (String .format ("Map key cannot be cast to %s" , keyClass .getName ()));
766
+ }
758
767
}
759
- if (entry .getValue () != null && !valueClass .isAssignableFrom (entry .getValue ().getClass ())) {
760
- if (entry .getValue () instanceof Number && NUMBER_CONVERTERS .containsKey (valueClass )) {
768
+ // Convert value if necessary
769
+ if (value != null && !valueClass .isAssignableFrom (value .getClass ())) {
770
+ if (value instanceof Number && NUMBER_CONVERTERS .containsKey (valueClass )) {
761
771
Function <Number , ?> converter = NUMBER_CONVERTERS .get (valueClass );
762
- entry . setValue (( V ) converter .apply ((Number ) entry . getValue ()) );
772
+ value = ( V ) converter .apply ((Number ) value );
763
773
} else {
764
774
throw new ClassCastException (String .format ("Map value %s, cannot be cast to %s" ,
765
- entry . getValue () .getClass (), valueClass .getName ()));
775
+ value .getClass (), valueClass .getName ()));
766
776
}
767
777
}
778
+ result .put (newKey , value );
768
779
}
769
- return value ;
780
+ return result ;
770
781
}
771
782
772
783
@ SuppressWarnings ("unchecked" )
0 commit comments