jeudi 9 juillet 2020

Mirror an object to another in java

Have two different classes: A and B. They have exactly the same field names. Suppose their definition is below:

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class A {
  private String attriA;
  private String attriB;
  private String attriC;
}

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class B {
  private String attriA;
  private String attriB;
  private String attriC;
}

Assume I have an instance of A, objectA, and I want to translate it into B. With all manual work, it'll look like:

B objectB = B.builder()
        .attriA(objectA.getAttriA())
        .attriB(objectA.getAttriB())
        .attriC(objectA.getAttriC())
        .build();

Question:

Seems I'm repeating those setters. Any library or approaches with which I don't have to write those repetitive setters? Feeling we may use reflection, but don't know exactly how.





Aucun commentaire:

Enregistrer un commentaire