Java - how to simplify my java
I am writing some java code in the Spring Framework.
I've got two beans, person and person1. They have a slightly different structure, that is to say the variable names for each differ slightly.
I'm trying to copy the details from one bean to the other. I only want to copy the value if the value is not null. I've seen an API called BeanUtils, but this will copy it regardless if it is null or not.
Here's my code:
if (person != null) 开发者_如何学Go{
if (person.getAddressDetails() != null) {
if (person.getAddressDetails().getStreetNumber() != null) {
person1.getAddressDetails().setStreetNo(person.getAddressDetails().getStreetNumber());
}
if (person.getAddressDetails().getStreetName() != null) {
person1.getAddressDetails().setStreetName(person.getAddressDetails().getStreetName());
}
}
if (person.getHomeDetails() != null) {
if (person.getHomeDetails().getPhoneNumber() != null) {
person1.getHomeDetails().setSPhoneNo(person.getHomeDetails().getPhoneNumber());
}
}
}
I have about 40 nodes that need to be copied over and this would create so much ugly code. Does anyone have a better way to do this? maybe if i make a mapping or something and then loop through it? not sure.
If not, does anyone know if i can make BeanUtils run a copy without copying the null values?
Reason is that the second bean, person1, already has a bunch of values. I only want to overwrite that if there are new values to overwrite it with.
As usual the variables are part of a much larger system and I can't standardise the names.
Thanks
Approach the problem from the other direction, your source data object should not care about constraints or business logic requirement of your target object.
That would be tight coupling and that is bad, especially if you are using Spring, you are doing exactly what an IoC container such as Spring it trying to help you not do.
Put the null checking
coding in your setXXX()
methods of the target object, that is the correct place to handle a business rule if you don't ever want to set the target properties if the source property is null
.
public setXXX(final String s)
{
if (s == null) { // do nothing }
else { this.xxx = s; }
}
then you could use whatever mapping strategy / library you want and not worry about the source data null
status. Blindly setting properties and letting the target decide when to ignore the incoming null
.
I wonder if Dozer might help you out.
精彩评论