mercredi 1 août 2018

What is the best code design to initialize all fields of pojo from a map and another json object

I am having a pojo as:

class CompositeDto 
{
  SampleDto ab;
  SampleDto bc;
  SampleDto cd;
  SampleDto de;
  SampleDto ef;
  CompositeDto(JsonObject x)
  {
    this.setAb
    (
      x.get("ab").getAsString(),
      SOME_MAP.get("ab"),
      SOME_OTHER_MAP.get("ab"),
      YET_ANOTHER_MAP.get("ab")
    );
    this.setBc
    (
      x.get("bc").getAsString(),
      SOME_MAP.get("bc"),
      SOME_OTHER_MAP.get("bc"),
      YET_ANOTHER_MAP.get("bc")
    );
    this.setCd
    (
      x.get("cd").getAsString(),
      SOME_MAP.get("cd"),
      SOME_OTHER_MAP.get("cd"),
      YET_ANOTHER_MAP.get("cd")
    );


    this.setDe
    (
      x.get("de").getAsString(),
      SOME_MAP.get("de"),
      SOME_OTHER_MAP.get("de"),
      YET_ANOTHER_MAP.get("de")
    );
    this.setEf
    (
      x.get("ef").getAsString(),
      SOME_MAP.get("ef"),
      SOME_OTHER_MAP.get("ef"),
      YET_ANOTHER_MAP.get("ef")
    );
  }
}

where SampleDto is as follows:

@Getter
@Setter
@AllArgsConstructor
class SampleDto    
{
  String a;
  String b;
  String c;
  String d;
}

My concern here is the repetitive setters in the constructor of CompositeDto. Is there any cleaner way of doing the same in a loop(because everything other than field names is in a loop) which will remove code repitition and tomorrow if we are adding a new field, we can add that in a constants file somewhere, and not add some more lines to this class. I was thinking of two ways. One is to replace the Dto with a hashmap with field names mapping to their values. But this defeats the basic purpose of using Java pojo classes. Another was to use reflection to fetch class field names, and then "create" the setter method name in the loop and to call it. But that is looking inside the class. So, I was not sure, whether its the best design to use. Is there any other cleaner approach to do the same?

Aucun commentaire:

Enregistrer un commentaire