Как вызвать все методы getter класса в al oop? - PullRequest
0 голосов
/ 02 марта 2020

У меня есть список объектов, и я хочу создать файл Excel из элементов списка, но не хочу указывать все столбцы по одному. Я хочу взять все свойства объекта в al oop и поместить в 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);
}

Я проверил "отражение", но не смог получить точное решение. Как я могу назвать всех получателей в al oop?

1 Ответ

1 голос
/ 03 марта 2020

Вы можете получить доступ к объявленным методам класса следующим образом:

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

 }```
...