在Java中如何将一个POJO的所有属性复制到另一个POJO?

9

我有一个第三方jar包中的POJO,我们不能直接向客户端公开。

ThirdPartyPojo.java

public class ThirdPartyPojo implements java.io.Serializable {

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

    //public setters and getters

}

上述类是我们如下使用的第三方jar的一部分。
ThirdPartyPojo result = someDao.getData(String id);

现在我们的计划是,由于ThirdPartyPojo是第三方jar包的一部分,我们不能直接将ThirdPartyPojo结果类型发送给客户端。我们想创建自己的pojo,该pojo将具有与ThirdPartyPojo.java类相同的属性。我们必须从ThirdPartyPojo.java设置数据到OurOwnPojo.java中,并按以下方式返回它。
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.

}

现在我想知道是否有一种最好的方法,可以在OurOwnPojo.java中拥有与ThirdPartyPojo.java相同的属性,并从ThirdPartyPojo.java填充数据到OurOwnPojo.java,并返回相同的内容?

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**

}

谢谢!


2
将 ThirdPartyPojo 类扩展到 OurOwnPojo 类中。 - Kamlesh Arya
3个回答

18

也许您正在搜索 Apache CommonsBeanUtils.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;
}

不错,我知道但是忘记了 :D - VedantK

2

org.springframework.beans.BeanUtils比apache aone更好:

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

1
不要误判源和目标pojos:
try {

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接