I've two objects objclient
and objserver
of the same type Object
,(i.e. Dog, Cat..)
when I receive objclient
in my endpoint I need to replace its attributes with the non-null ones in objserver
without doing explicitly, for example :
private void eraser(Object clientObject, Object serverObject){
//set only non null attributes of serverObject to clientObject
}
CodePudding user response:
You can use e.g. ModelMapper if you want to map values between different java objects without explicitly having to map every single field.
CodePudding user response:
BeanUtils.copyProperties is very common in spring-boot projects, we can use it with passing ignoreProperties (null case) & we can find the null case by using a custom method like below:
private ClientObject eraser(ClientObject clientObject, ServerObject serverObject){
BeanUtils.copyProperties(serverObject, clientObject, getNullPropertyNames(serverObject));
return clientObject;
}
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
It will set only non null attributes of serverObject to clientObject.