Try something like that:
public static Field acharField(Class<?> onde, String nome) throws NoSuchFieldException {
if (onde == null) throw new NullPointerException();
if (nome == null) throw new NullPointerException();
NoSuchFieldException excecao = null;
for (Class<?> c = onde; c != null; c = c.getSuperclass()) {
try {
return c.getDeclaredField(nome);
} catch (NoSuchFieldException e) {
if (excecao == null) excecao = e;
}
}
throw excecao;
}
The method getDeclaredField(String)
looking for Field
in the class in question, even if it is private. However, this method doesn’t look in the superclasses, which is why this code uses an iteration to try in the superclasses until it finds.
He will look for the Field
in class and if not find, will try the superclasses until arriving in Object
. If indeed find nowhere, launches the first NoSuchFieldException
obtained. If any parameter is null
, spear NullPointerException
.
See in ideone a test of this method working.