-1

I have two pojos.

public class Pojo1 implements Serializable {

    private static final long serialVersionUID = 1302290920579795856L;

    private Long id;
    private String idNumber; 
    private String vendorNumber; 
    private Date expires;

    // Getters and setters for each one
}

public class Pojo2 implements Serializable {

    private static final long serialVersionUID = 1302290920579795856L;

    private Long id;
    private String idNumber; 
    private String vendorNumber; 
    private Date expires;
    private String otherData;

    // Getters and setters for each one
}

Is there a Java API that I can use to create a Pojo1 from a Pojo2 automatically?

I.e.:

Pojo1 newPojo1 = SomeLibrary.fromPojoWithLikeNamedFields(pojo2);

// newPojo1 now has all the fields that had the same name from pojo2
Nicholas DiPiazza
  • 10,029
  • 11
  • 83
  • 152

1 Answers1

-1

won't a copy constructor do the job?,

public Pojo1(Pojo2 pojo2){
    this.id = pojo2.getId();
    this.idNumber = pojo2.getIdNumber();
    this.vendorNumber = pojo2.getVendorNumber();
    this.expires = pojo2.getExpires();
}

and then use as such,

Pojo1 newPojo1 = new Pojo1(pojo2);

or am I misunderstanding something...?

mre
  • 43,520
  • 33
  • 120
  • 170
  • 1
    +1 (sry, over my daily limit). I think the same as you. Only thing I would change is to call getters, because his attributes are private. – jlordo Dec 04 '12 at 17:31
  • He doesn't want to have to write the copy constructor in the first place. – Thorn G Dec 04 '12 at 17:31
  • @jlordo, Excellent point, I completely overlooked that; modified code to use getters! :) – mre Dec 04 '12 at 17:32
  • @TomG, I think including this copy constructor makes much more sense than using a third party library. – mre Dec 04 '12 at 17:49
  • 1
    I totally agree, and did not downvote you -- just pointing out that the original question implied a generic approach to any two POJOs with similar bean properties, as I read it. – Thorn G Dec 04 '12 at 18:35
  • I'm downvoting this - doesn't use reflection - this serves no purpose i can already copy paste each one – Nicholas DiPiazza Dec 04 '12 at 18:40