ループ内のクラスのすべてのgetterメソッドを呼び出す方法?

クリスGarsonn:

私は、オブジェクトのリストを持っていると私は、リスト内の項目から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列を取得していますが、私はすべてのプロパティを取得したいが、すべてのコードを一さようなら1をハードコードしないで...

何かのようなもの :

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

私は「反射」をチェックしますが、正確な解を得ることができませんでした。どのように私は、ループ内のすべてのゲッターを呼び出すことができますか?

SMS :

あなたはそのように、クラスの宣言されたメソッドにアクセスすることができます:

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

 }```

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=21146&siteId=1