How to get a specific field of a class even though it is inherited

Asked

Viewed 64 times

-2

I am facing problems while trying to get a field of a class, I am always getting the error NoSuchFieldException. What is known is that this field is inherited and deprived of another class, but the parent class may be a daughter of another, and so on.

What I need is to find this field even if she is another’s daughter, and so on.

Obs:

  1. Any doubt do not hesitate to take.
  2. Any example of code would be very useful.

1 answer

2


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.