From 6838395d50a041603ede86b330afcfa4d58a61ab Mon Sep 17 00:00:00 2001 From: Mahmoud Ben Hassine Date: Sat, 9 Sep 2023 22:27:03 +0200 Subject: [PATCH] Use getter if available when retrieving field value Resolves #464 --- .../java/org/jeasy/random/EasyRandom.java | 2 +- .../jeasy/random/util/ReflectionUtils.java | 25 ++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/jeasy/random/EasyRandom.java b/src/main/java/org/jeasy/random/EasyRandom.java index 3f24cad6..c1018a57 100644 --- a/src/main/java/org/jeasy/random/EasyRandom.java +++ b/src/main/java/org/jeasy/random/EasyRandom.java @@ -222,7 +222,7 @@ private void populateField(final Field field, final T result, final Randomiz if (exclusionPolicy.shouldBeExcluded(field, context)) { return; } - if (!parameters.isOverrideDefaultInitialization() && getFieldValue(result, field) != null && !isPrimitiveFieldWithDefaultValue(result, field)) { + if (!parameters.isOverrideDefaultInitialization() && getProperty(result, field) != null && !isPrimitiveFieldWithDefaultValue(result, field)) { return; } fieldPopulator.populateField(result, field, context); diff --git a/src/main/java/org/jeasy/random/util/ReflectionUtils.java b/src/main/java/org/jeasy/random/util/ReflectionUtils.java index 3f3950f1..623a3e9e 100644 --- a/src/main/java/org/jeasy/random/util/ReflectionUtils.java +++ b/src/main/java/org/jeasy/random/util/ReflectionUtils.java @@ -154,6 +154,29 @@ public static void setFieldValue(final Object object, final Field field, final O field.setAccessible(access); } + /** + * Get a value of a field of a target object. If the target object provides + * a getter for the field, this getter will be used. Otherwise, the field + * will be get using reflection. + * + * @param object instance to get the property value + * @param field field to get the property value + * @throws IllegalAccessException if the property cannot be retrieved + */ + public static Object getProperty(final Object object, final Field field) throws IllegalAccessException { + try { + Optional getter = getReadMethod(field); + if (getter.isPresent()) { + return getter.get().invoke(object); + } else { + return getFieldValue(object, field); + } + } catch (IllegalAccessException | InvocationTargetException e) { + // otherwise, get field using reflection + return getFieldValue(object, field); + } + } + /** * Get the value (accessible or not accessible) of a field of a target object. * @@ -198,7 +221,7 @@ public static boolean isPrimitiveFieldWithDefaultValue(final Object object, fina if (!fieldType.isPrimitive()) { return false; } - Object fieldValue = getFieldValue(object, field); + Object fieldValue = getProperty(object, field); if (fieldValue == null) { return false; }