user755806
user755806

Reputation: 6825

copying all properties of one pojo to another in java?

I have below POJO of some third party jar which we cannot expose to our clients directly.

ThirdPartyPojo.java

public class ThirdPartyPojo implements java.io.Serializable {

    private String name;
    private String ssid;
    private Integer id;

    //public setters and getters

}

Above class is part of third party jar which we are using as below.

ThirdPartyPojo result = someDao.getData(String id);

Now our plan is as ThirdPartyPojo is part of third party jar, we cannot send ThirdPartyPojo result type directly to clients. we want to create our own pojo which will have same properties as ThirdPartyPojo.java class. we have to set the data from ThirdPartyPojo.java to OurOwnPojo.java and return it as below.

public OurOwnPojo getData(String id){

    ThirdPartyPojo result = someDao.getData(String id)

    OurOwnPojo response = new OurOwnPojo(result);

    return response;

    //Now we have to populate above `result` into **OurOwnPojo** and return the same.

}

Now I want to know if there is a best way to have same properties in OurOwnPojo.java as ThirdPartyPojo.java and populate the data from ThirdPartyPojo.java to OurOwnPojo.java and return the same?

public class OurOwnPojo implements java.io.Serializable {

    private ThirdPartyPojo pojo;

    public OurOwnPojo(ThirdPartyPojo pojo){

         this.pojo = pojo
    }


    //Now here i need to have same setter and getters as in ThirdPartyPojo.java

    //i can get data for getters from **pojo**

}

Thanks!

Upvotes: 9

Views: 26017

Answers (3)

Zon
Zon

Reputation: 19918

Don't misjudge origin and destination pojos:

try {

  BeanUtils.copyProperties(new DestinationPojo(), originPojo);

} catch (IllegalAccessException | InvocationTargetException e) {
  e.printStackTrace();
}

Upvotes: 1

feuyeux
feuyeux

Reputation: 1196

org.springframework.beans.BeanUtils is better than apache aone:

Task subTask = new Task();
org.springframework.beans.BeanUtils.copyProperties(subTaskInfo.getTask(), subTask);

Upvotes: 2

Masudul
Masudul

Reputation: 21981

Probably you are searching Apache Commons BeanUtils.copyProperties.

public OurOwnPojo getData(String id){

  ThirdPartyPojo result = someDao.getData(String id);
  OurOwnPojo myPojo=new OurOwnPojo();

  BeanUtils.copyProperties(myPojo, result);
         //This will copy all properties from thirdParty POJO

  return myPojo;
}

Upvotes: 18

Related Questions