我有一个对象列表,我想从列表中的项目创建一个 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?
最佳答案
您可以通过这种方式访问类的声明方法:
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;
}
}```
关于java - 如何循环调用一个类的所有getter方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60496409/