如何在循环中调用 class 的所有 getter 方法?

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

我有一个对象列表,我想从列表中的项目创建一个 excel 文件,但不想一一指定所有列。我想在循环中获取对象的所有属性并放入 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");
        }

正如您在代码中看到的那样,我只获得了 4 列,但我想获得所有属性,但不想对所有代码进行硬编码......

类似于:

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

我检查了"reflection",但无法得到确切的解决方案。如何在循环中调用所有 getter?

您可以这样访问 class 的已声明方法:

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;
    }

 }```