'Parsing two objects into one
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
}
Solution 1:[1]
You can use e.g. ModelMapper if you want to map values between different java objects without explicitly having to map every single field.
Solution 2:[2]
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.
Solution 3:[3]
Actually the best solution comparing to @Rakib's one is:
private void erase(Object clientObject, Object defaultObject) throws IllegalAccessException, NoSuchFieldException {
Field[] Fields = defaultObject.getClass().getDeclaredFields();
for (Field field : Fields) {
field.setAccessible(true);
Object value = field.get(defaultObject);
if(value !=null)
field.set(clientObject,value);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tbjorch |
Solution 2 | Rakib Hasan |
Solution 3 | Abdessalam Idali Lahcen |