Try something like this:
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)
looks for Field
in the class in question, even if it is private. However, this method does not look in superclasses, which is why this code uses an iteration to go through superclasses until you find it.
It will look for Field
in the class and if it does not find it, it will try the superclasses until it reaches Object
. If in fact you can not find anywhere, cast the first% of% obtained. If any parameter is NoSuchFieldException
, it throws null
.
See in ideone a test of this method working.