How to get a specific field from a class even being inherited

-3

I'm having trouble trying to get a field of a class, I'm always getting the error NoSuchFieldException . What is known is that this field is inherited and deprived of another class, but the parent class can be a child of another, and so on.

What I need is to find this field even though it is the daughter of another, and so on.

Note:

  • Any questions do not hesitate to take.
  • Any code example would be very useful.
  • asked by anonymous 22.07.2018 / 20:26

    1 answer

    2

    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.

        
    22.07.2018 / 20:31