Skip to content

Instantly share code, notes, and snippets.

@eyalgo
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyalgo/8833783 to your computer and use it in GitHub Desktop.
Save eyalgo/8833783 to your computer and use it in GitHub Desktop.
Showing how to use reflection to test inner fields
// Somewhere in a different utility class for testing
@SuppressWarnings("unchecked")
public static <T> T realObjectFromField(Class<?> clazz, String fieldName, Object object) {
Field declaredField = accessibleField(clazz, fieldName);
try {
return (T) declaredField.get(object);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
private static Field accessibleField(Class<?> clazz, String fieldName) {
try {
Field declaredField = clazz.getDeclaredField(fieldName);
declaredField.setAccessible(true);
return declaredField;
} catch (NoSuchFieldException | SecurityException e) {
throw new RuntimeException(e);
}
}
// This is how we use it in a test method
import static mypackage.ReflectionUtils.realObjectFromField;
ItemFiltersMapperByFlag mapper = realObjectFromField(ItemsFilterExecutor.class, "filtersMapper", filterExecutor);
assertNotNull("mapper is null. Check wiring", mapper);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment