Skip to content
This repository has been archived by the owner on May 26, 2020. It is now read-only.

Commit

Permalink
Merge 4e0e592 into 3ad5c03
Browse files Browse the repository at this point in the history
  • Loading branch information
Allan Mckenzie committed Dec 13, 2018
2 parents 3ad5c03 + 4e0e592 commit 38f4cef
Showing 1 changed file with 28 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -75,27 +75,35 @@ public static Optional<Method> annotatedMethod(final Class<?> classWithMethod, f
*/
public static void setField(final Object object, final String fieldName, final Object fieldValue) {

final Field field = getField(object.getClass(), fieldName);
try {
final Field field = getField(object.getClass(), fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
} catch (final IllegalAccessException e) {
} catch (IllegalAccessException e) {
throw new ReflectionException(format("Unable to access field '%s' on class %s", fieldName, object.getClass().getName()), e);
}
}

/**
* Searches for a field in the given class by reflection
*
* @param classWithField - class type
* @param fieldName - name of field in class
* @param aClass - class type
* @param fieldName - name of field in class
* @return - field belonging to the given classWithField with the given fieldName
*/
public static Field getField(final Class<?> classWithField, final String fieldName) {
return stream(classWithField.getDeclaredFields())
.filter(f -> f.getName().equals(fieldName))
.findFirst()
.orElseThrow(() -> new ReflectionException(format("No field named '%s' found on class %s", fieldName, classWithField.getName())));
@SuppressWarnings("CatchMayIgnoreException")
public static Field getField(final Class<?> aClass, final String fieldName) {

for (Class<?> currentClass = aClass; currentClass != Object.class; currentClass = currentClass.getSuperclass()) {
if (hasField(fieldName, currentClass)) {
try {
return currentClass.getDeclaredField(fieldName);
} catch (final NoSuchFieldException thisWillNeverHappen) {
}
}
}

throw new ReflectionException(format("No field named '%s' found on class %s", fieldName, aClass.getName()));
}

/**
Expand All @@ -120,4 +128,15 @@ public static <T> T getValueOfField(
throw new ReflectionException(format("Unable to access field '%s' on class %s", fieldName, object.getClass().getName()), e);
}
}

private static boolean hasField(final String fieldName, final Class<?> aClass) {
final Field[] declaredFields = aClass.getDeclaredFields();

if (declaredFields == null) {
return false;
}

return stream(declaredFields)
.anyMatch(field -> field.getName().equals(fieldName));
}
}

0 comments on commit 38f4cef

Please sign in to comment.