Created
March 22, 2020 17:28
-
-
Save horatiu-udrea/a453fc7afaecca77bdfcbfd2188db386 to your computer and use it in GitHub Desktop.
Get a private Field from up the hierarchy
This file contains hidden or 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
/** | |
* Returns the first {@link Field} in the hierarchy for the specified name | |
*/ | |
private static Field getField(Class<?> clazz, String name) throws NoSuchFieldException | |
{ | |
Field field = null; | |
while (clazz != null && field == null) | |
{ | |
try | |
{ | |
field = clazz.getDeclaredField(name); | |
} | |
catch (Exception ignored) | |
{ | |
} | |
clazz = clazz.getSuperclass(); | |
} | |
return Optional.ofNullable(field).orElseThrow(NoSuchFieldException::new); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment