Java Reflection: Iterate Entity Attributes

In Java, you can use reflection to iterate through a class and retrieve its attributes. Here is an example code:

import java.lang.reflect.Field;

public class Main {
    public static void main(String[] args) {
        Person person = new Person("John", 30, "Male");

        Class<?> clazz = person.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                System.out.println(field.getName() + ": " + field.get(person));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}

class Person {
    private String name;
    private int age;
    private String gender;

    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
}

In this example, we first create a Person class and instantiate a Person object. We then use reflection to access all the properties of the Person class and retrieve the values of these properties using the get method of the Field class. It’s important to note that if the property is private, you need to call setAccessible(true) method to allow access to private properties.

bannerAds