9

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!

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
user755806
  • 6,565
  • 27
  • 106
  • 153

3 Answers3

18

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;
}
Masudul
  • 21,823
  • 5
  • 43
  • 58
2

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

Task subTask = new Task();
org.springframework.beans.BeanUtils.copyProperties(subTaskInfo.getTask(), subTask);
feuyeux
  • 1,158
  • 1
  • 9
  • 26
1

Don't misjudge origin and destination pojos:

try {

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

} catch (IllegalAccessException | InvocationTargetException e) {
  e.printStackTrace();
}
Zon
  • 18,610
  • 7
  • 91
  • 99