有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个对象列表,我想从列表中的项目创建一个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);
}

我检查了“反射”,但无法得到精确的解。如何调用循环中的所有getter


共 (1) 个答案

  1. # 1 楼答案

    您可以通过以下方式访问类的声明方法:

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