lundi 14 août 2017

Loop over object setters java

I have a POJO object and a collection of appropriate data.

import java.util.ArrayList;
import java.util.List;

public class TestPojo {

private String name;
private String number;
private String id;
private String sex;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getNumber() {
    return number;
}

public void setNumber(String number) {
    this.number = number;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getSex() {
    return sex;
}

public void setSex(String sex) {
    this.sex = sex;
}

public static void main(String[] args) {

    TestPojo test = new TestPojo();

    List<String> sampleData = new ArrayList<>();
    sampleData.add("Bob");
    sampleData.add("641-613-623");
    sampleData.add("id-1451");
    sampleData.add("Male");

    test.setName(sampleData.get(0));
    test.setNumber(sampleData.get(1));
    test.setId(sampleData.get(2));
    test.setSex(sampleData.get(3));
    }
}

My question is how can i fill my POJO object with data in a loop? Is it posible to iterate all object setters and set data from List in appropriate places? I know that reflection can help in this case.





Aucun commentaire:

Enregistrer un commentaire