Java – how to simplify my java
I wrote some java code in the spring framework
I have two beans, man and man 1 Their structure is slightly different, that is, each variable name is slightly different
I'm trying to copy details from one bean to another I just want to copy the value if the value is not null I have seen an API called BeanUtils, but it will be copied whether it is null or not
This is my code:
if (person != null) { 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 to copy, which will produce so much ugly code Does anyone have a better way to do this? Maybe if I do a mapping or something and loop it? uncertain.
If not, does anyone know if I can make BeanUtils run a copy without copying null values?
The reason is that the second bean, person1, already has a pile of values If there is a new value to overwrite it, I just want to overwrite it
As usual, variables are part of a larger system, and I can't standardize names
thank you
Solution
Dealing with the problem in another direction, your source data object should not care about the constraints or business logic requirements of the target object
This will be tightly coupled, which is not good, especially if you use spring, you are making an IOC container like it, which tries to help you not to do it
Put the null check code in the setXXX () method of the target object. If you don't want to set the target property when the source property is null, this is the right place to process business rules
public setXXX(final String s) { if (s == null) { // do nothing } else { this.xxx = s; } }
Then you can use any mapping strategy / library you want without worrying about the null state of the source data Set the property blindly and let the target decide when to ignore the incoming null