vendredi 18 juin 2021

Map imported Excel columns to Java object attributes

I have a small Java app that parses Excel file (using Apache POI library). Now I want to map column values to Java object and I'm looking for best solution or pattern for doing this task.

For example, Java object is Customer with two attributes - name and email:

public class Customer {
    private String name;
    private String email;
    ... constructor, getters, setters
}

Excel file can have many columns, but it contains also two named name and email that I want to map to my Customer object's attributes in Java.

For example:

I loop through cells and know that indexes of columns for my Customer object are 0 and 2. I iterate than each row and if cell index is 0 I assign it's value to name and if 2 I assign it to email, but it's really hard-coded and I think there must be simpler solution or some pattern.

Can I put Customer attributes in Enum, then compare them with Excel column names and map in some data struct their order so that if I update Customer object I can easily add another Enum value without hard-coding attributes names in my parsing logic?

Aucun commentaire:

Enregistrer un commentaire