[英]Ignoring null fields when mapping from one object to another (Transfer Object) in java?
I'm writing a transfer object which simply maps an object coming back from a webservice to my own object: Car A to Car B. 我正在编写一个传输对象,该对象只是将一个从Web服务返回的对象映射到我自己的对象:Car A到CarB。
a Car class has a mileage property. 汽车类具有里程属性。
CarB.setMileage(CarA.getMileage()); //if the CarA.getMileage() is null, then my setter fails and I get a nullPointerException
I have 50 fields, and am I correct that I just need write 50 separate checks for null before setting my fields? 我有50个字段,我是否正确,我只需要在设置字段之前写50个单独的null检查?
ie, 即
if (CarA.getMileage() != null) {
CarB.setMileage(CarA.getMileage());
}
Is there a way to avoid writing 50 separate if !=null
check statements? 有没有一种方法可以避免编写50个单独的if !=null
检查语句?
Try using Dozer mapping. 尝试使用推土机映射。 It is a good tool and it can help ignoring null values too. 这是一个很好的工具,它也可以帮助忽略空值。 It can be used to map two object programatically and using XML. 它可以用于以编程方式并使用XML映射两个对象。 You do not to specify any mapping between two fields of objects if attribute names in them are same. 如果对象的两个字段之间的属性名称相同,则不要指定任何映射。 Following is the link: 以下是链接:
http://dozer.sourceforge.net/documentation/faq.html http://dozer.sourceforge.net/documentation/faq.html
You can create a static factory method in CarB
: 您可以在CarB
创建静态工厂方法:
// carA is of type CarA returned by the web service
CarB carB = CarB.fromCarA(carA);
All null checks etc would then be done in that factory method. 然后,所有空检查等都将在该工厂方法中完成。 Sample code: 样例代码:
public class CarB
{
//....
public static CarB fromCarA(final CarA carA)
{
if (carA == null)
throw new NullPointerException("Where is my car???");
final CarB ret = new CarB();
// Supposing CarA returns an Integer...
final Integer mileage = carA.getMileage();
if (mileage != null)
ret.setMileage(mileage);
// etc etc, then
return ret;
}
// etc
}
Little common but the better way is a common method
in your bean Class
很少见但更好的方法是bean Class
的通用method
function String checkForNull(String str){
//check for null and return corresponding
}
and then 接着
CarB.setMileage(checkForNull(CarA.getMileage()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.