简体   繁体   English

在java中将一个pojo的所有属性复制到另一个pojo?

[英]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. 我有一些第三方罐子的POJO,我们不能直接向客户透露。

ThirdPartyPojo.java 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. 上面的类是我们正在使用的第三方jar的一部分,如下所示。

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. 现在我们的计划是由于ThirdPartyPojo是第三方jar的一部分,我们不能直接向客户端发送ThirdPartyPojo结果类型。 we want to create our own pojo which will have same properties as ThirdPartyPojo.java class. 我们想创建自己的pojo,它将具有与ThirdPartyPojo.java类相同的属性。 we have to set the data from ThirdPartyPojo.java to OurOwnPojo.java and return it as below. 我们必须将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.

}

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? 现在我想知道是否有最好的方法在OurOwnPojo.java具有与ThirdPartyPojo.java相同的属性, OurOwnPojo.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**

}

Thanks! 谢谢!

Probably you are searching Apache Commons BeanUtils.copyProperties . 可能您正在搜索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;
}

org.springframework.beans.BeanUtils is better than apache aone: org.springframework.beans.BeanUtils比apache更好:

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

Don't misjudge origin and destination pojos: 不要误判原产地和目的地pojos:

try {

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM