Last active
August 29, 2015 13:56
-
-
Save eyalgo/8833783 to your computer and use it in GitHub Desktop.
Showing how to use reflection to test inner fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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