Skip to content

Commit

Permalink
Use getter if available when retrieving field value
Browse files Browse the repository at this point in the history
Resolves #464
  • Loading branch information
fmbenhassine committed Sep 9, 2023
1 parent 365a83d commit 6838395
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/main/java/org/jeasy/random/EasyRandom.java
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ private <T> 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);
Expand Down
25 changes: 24 additions & 1 deletion src/main/java/org/jeasy/random/util/ReflectionUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Method> 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.
*
Expand Down Expand Up @@ -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;
}
Expand Down

0 comments on commit 6838395

Please sign in to comment.