Search code examples
javaspringobjectreflectiongetter-setter

How to call all getter methods of a class in a loop?


I have an object list and I want to create an excel file from the items in list but do not want to specify all columns one bye one. I want to take all properties of an object in a loop and put to excel.

for (CustomerDTO customerDto : customerDtoList) {
            Row row = sheet.createRow(rowNumber++);
            row.createCell(0).setCellValue(customerDto.getName());
            row.createCell(1).setCellValue(customerDto.getSurname());
            row.createCell(2).setCellValue(customerDto.getAddress());
            row.createCell(3).setCellValue(customerDto.isActive() ? "Enabled" : "Disabled");
        }

As you see in code I am only getting 4 columns but I want to get all properties but not hardcode all codes one bye one...

something like :

int index = 0
for (CustomerDTO customerDto : customerDtoList) {
index++;
row.createCell(index).setCellValue(customerDto.GETTERBLABLA);
}

I checked the "reflection", but could not get exact solution. How can I call all getters in a loop ?


Solution

  • You could access declared methods of a class that way:

    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class Other {
    
        public static void main(String [] args) {
    
            Person p = new Person("Max", 12);
            Class<?> c = p.getClass();
            Method[] allMethods = c.getDeclaredMethods();
    
            System.out.print( "Person's attributes: ");
            for (Method m : allMethods) {
                m.setAccessible(true);
                String result;
                try {
                    result = m.invoke(p).toString();
                    System.out.print(result + " ");
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                 }
    
            }
        }
    }
    
    class Person {
        String name;
        int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public int getAge() {
            return age;
        }
    
     }```