Java Reflection nested objects

Asked

Viewed 46 times

1

Hello, good afternoon everyone.

I’m studying java Reflection and my question is whether it would be possible and how to pick up nested objects dynamically as in the example below:

public class Rg{
       Integer numRg;
}
public class Pessoa{ 
       String nome;
       Rg rg;
}

Thank you very much!

1 answer

2


Yes, you can access the attributes of a class through the functions getDeclaredFields() and getType(), and keep repeating until you get where you want.

Class pessoaClass = Pessoa.class;
Field[] pessoaFields = pessoaClass.getDeclaredFields();

for (Field pessoaField : pessoaFields) {
    if (pessoaField.getName() == "rg") {
        Class rgClass = pessoaField.getType();
        Field[] rgFields = rgClass.getDeclaredFields();
        for (Field rgField : rgFields) {
            System.out.println(rgField.getName());
        }
    }
}
  • Thank you very much for your reply Marlon!

Browser other questions tagged

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