Move null check logic to separate method

Move null check logic to separate method
This commit is contained in:
Himanshu Mantri 2017-06-06 15:20:48 +05:30
parent 7cf3afbd79
commit 5b9a125581
1 changed files with 24 additions and 15 deletions

View File

@ -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;
}
} }