我有一个对象列表,我想从列表中的项目创建一个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);
}
我检查了“反射”,但无法获得确切的解决方案。如何在循环中调用所有吸气剂?
最佳答案
您可以通过以下方式访问类的声明方法:
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/