我有一些第三方罐子的POJO,我们不能直接向客户透露。
third party PO Jo.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,它将具有与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**
}
谢谢!
可能你正在寻找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比apache更好:
Task subTask = new Task();
org.springframework.beans.BeanUtils.copyProperties(subTaskInfo.getTask(), subTask);
不要误判原产地和目的地pojos:
try {
BeanUtils.copyProperties(new DestinationPojo(), originPojo);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}