Move null check logic to separate method
Move null check logic to separate method
This commit is contained in:
parent
7cf3afbd79
commit
5b9a125581
|
@ -3,9 +3,10 @@ package com.baeldung.reflection.util;
|
||||||
import java.beans.Introspector;
|
import java.beans.Introspector;
|
||||||
import java.beans.PropertyDescriptor;
|
import java.beans.PropertyDescriptor;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
import com.baeldung.reflection.model.Customer;
|
import com.baeldung.reflection.model.Customer;
|
||||||
|
|
||||||
|
@ -15,20 +16,28 @@ public class Utils {
|
||||||
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
|
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
|
||||||
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
|
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
|
||||||
|
|
||||||
List<String> nullProps = new ArrayList<String>();
|
List<String> nullProps = propDescList.stream()
|
||||||
|
.filter(nulls(customer))
|
||||||
propDescList.stream().forEach(p -> {
|
.map(PropertyDescriptor::getName)
|
||||||
Method getterMethod = p.getReadMethod();
|
.collect(Collectors.toList());
|
||||||
try {
|
|
||||||
if (getterMethod != null && getterMethod.invoke(customer) == null) {
|
|
||||||
// If the value if null for that field
|
|
||||||
nullProps.add(p.getName());
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
|
||||||
// Handle the exception
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return nullProps;
|
return nullProps;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
|
||||||
|
Predicate<PropertyDescriptor> isNull = new Predicate<PropertyDescriptor>() {
|
||||||
|
@Override
|
||||||
|
public boolean test(PropertyDescriptor pd) {
|
||||||
|
Method getterMethod = pd.getReadMethod();
|
||||||
|
boolean result = false;
|
||||||
|
try {
|
||||||
|
result = (getterMethod != null && getterMethod.invoke(customer) == null);
|
||||||
|
} catch (Exception e) {
|
||||||
|
// Handle the exception
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
return isNull;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue