Generic way to update pojos via getters and setters

后端 未结 2 1298
小鲜肉
小鲜肉 2021-02-15 16:42

Let\'s say I have POJO with getters and setters of different types. I want to write some generic algorithm for updating data from one to another based on just defining getters a

2条回答
  •  北海茫月
    2021-02-15 17:21

    I know you already have an answer but for anyone needing something like this in the future: I have developed a small library around this context - datus.

    Here is an example which shows some of its features:

    class Person {
      //getters + setters omitted for brevity
      private String firstName;
      private String lastName;
    }
    
    class PersonDTO {
      //getters + setters + empty constructor omitted for brevity
      private String firstName;
      private String lastName;
    }
    
      //the mutable API defines a mapping process by multiple getter-setter steps
      Mapper mapper = Datus.forTypes(Person.class, PersonDTO.class).mutable(PersonDTO::new)
          .from(Person::getFirstName).into(PersonDTO.setFirstName)
          .from(Person::getLastName)
          .given(Objects::nonNull, ln -> ln.toUpperCase()).orElse("fallback")
          .into(PersonDTO::setLastName)
          .from(/*...*/).into(/*...*/)
          .build();
    
      Person person = new Person();
    person.setFirstName("firstName");
        person.setLastName(null);
        PersonDTO personDto = mapper.convert(person);
    /*
        personDto = PersonDTO [
            firstName = "firstName",
            lastName = "fallback"
        ]
    */
        person.setLastName("lastName");
        personDto = mapper.convert(person);
    /*
        personDto = PersonDTO [
            firstName = "firstName",
            lastName = "LASTNAME"
        ]
    */
    

提交回复
热议问题