Přidat otázku mezi oblíbenéZasílat nové odpovědi e-mailemVyřešeno Java - Jak získat všechny fields objektu jako String?

Dobrý den,

Mám třídu Example. Z ní vytvořím objekt.

Example example = new Example(4, 8, "four", "eight");

Jak napíšu metodu, která mi vrátí všechny fields jako ArrayList<String>

import java.lang.reflect.Field;
import java.util.ArrayList;

public class Example {

    int first, second;
    String third, fourth;

    public Example(int first, int second, String third, String fourth) {
        this.first = first;
        this.second = second;
        this.third = third;
        this.fourth = fourth;
    }

    public ArrayList<String> getAllFields() {
        Field fields[] = this.getClass().getDeclaredFields();
        ArrayList<String> list = new ArrayList<>(fields.length);
        for (Field field : fields) {
            try {
                if (field.getGenericType().getTypeName().equals("int")) {        
                    
                } else {
                    
                }
            } catch (IllegalArgumentException ex) {
                System.out.println(ex.getMessage());
            }
        }
        return list;
    }
}

V podmínce dokážu rozlišit datový typ. Pomocí field.getName() můžu zjistit jméno fieldu, ale mám problém ho dostat do pole respektive převést na String.

Prosím Vás o radu

Děkuji

PS. Pochopitelně jsem to zkoušel, ale nešlo mi to a psát tam špatný kód nebudu.

Odpověď na otázku

1 Zadajte svou přezdívku:
2 Napište svou odpověď:
3 Pokud chcete dostat ban, zadejte libovolný text:

Zpět do poradny