From 54239fe9e8b9977b40ae665e261d34b8409a8d8f Mon Sep 17 00:00:00 2001 From: Mahmoud Ben Hassine Date: Fri, 15 Sep 2023 22:44:15 +0200 Subject: [PATCH] Refine contribution #718 - Rename variables - Update javadoc - Add type check before cast - Update code formatting --- .../batch/item/ExecutionContext.java | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ExecutionContext.java b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ExecutionContext.java index 8ebe1ce1c9..3fb0c2c4db 100644 --- a/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ExecutionContext.java +++ b/spring-batch-infrastructure/src/main/java/org/springframework/batch/item/ExecutionContext.java @@ -256,40 +256,44 @@ public Object get(String key) { } /** - * Typesafe getter for the value represented by the provided key, with cast to given class. - * + * Typesafe getter for the value represented by the provided key, with cast to given + * class. * @param key The key to get a value for - * @param clazz The class of return type + * @param type The class of return type * @param Type of returned value - * @return The value of given type represented by the given key or {@code null} if the key - * is not present + * @return The value of given type represented by the given key or {@code null} if the + * key is not present */ @Nullable - public V get(String key, Class clazz) { + public V get(String key, Class type) { Object value = this.map.get(key); if (value == null) { return null; } - return get(key, clazz, null); + return get(key, type, null); } /** - * Typesafe getter for the value represented by the provided key, with cast to given class. - * + * Typesafe getter for the value represented by the provided key, with cast to given + * class. * @param key The key to get a value for * @param type The class of return type * @param defaultValue Default value in case element is not present * @param Type of returned value - * @return The value of given type represented by the given key or {@code null} if the key - * is not present + * @return The value of given type represented by the given key or the default value + * if the key is not present */ @Nullable - public V get(String key, Class clazz, @Nullable V defaultValue) { + public V get(String key, Class type, @Nullable V defaultValue) { Object value = this.map.get(key); if (value == null) { return defaultValue; } - return clazz.cast(value); + if (!type.isInstance(value)) { + throw new ClassCastException("Value for key=[" + key + "] is not of type: [" + type + "], it is [" + "(" + + value.getClass() + ")" + value + "]"); + } + return type.cast(value); } /**