Skip to content

Instantly share code, notes, and snippets.

@horatiu-udrea
Created March 22, 2020 17:28
Show Gist options
  • Save horatiu-udrea/a453fc7afaecca77bdfcbfd2188db386 to your computer and use it in GitHub Desktop.
Save horatiu-udrea/a453fc7afaecca77bdfcbfd2188db386 to your computer and use it in GitHub Desktop.
Get a private Field from up the hierarchy
/**
* 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