1. Overview
In this quick article, we’ll use the Java 8 Stream API and the Introspector class – to invoke all getters found in a POJO.
We will create a stream of getters, inspect return values and see if a field value is null.
2. Setup
The only setup we need is to create a simple POJO class:
public class Customer { private Integer id; private String name; private String emailId; private Long phoneNumber; // standard getters and setters }
3. Invoking Getter Methods
We’ll analyze the Customer class using Introspector; this provides an easy way for discovering properties, events, and methods supported by a target class.
We’ll first collect all the PropertyDescriptor instances of our Customer class. PropertyDescriptor captures all the info of a Java Bean property:
PropertyDescriptor[] propDescArr = Introspector .getBeanInfo(Customer.class, Object.class) .getPropertyDescriptors();
Let’s now go over all PropertyDescriptor instances, and invoke the read method for every property:
return Arrays.stream(propDescArr) .filter(nulls(customer)) .map(PropertyDescriptor::getName) .collect(Collectors.toList());
The nulls predicate we use above checks if the property can be read invokes the getter and filters only null values:
private static Predicate<PropertyDescriptor> nulls(Customer customer) { return = pd -> { Method getterMethod = pd.getReadMethod(); boolean result = false; return (getterMethod != null && getterMethod.invoke(customer) == null); }; }
Finally, let’s now create an instance of a Customer, set a few properties to null and test our implementation:
@Test public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() { Customer customer = new Customer(1, "John", null, null); List<String> result = Utils.getNullPropertiesList(customer); List<String> expectedFieldNames = Arrays .asList("emailId","phoneNumber"); assertTrue(result.size() == expectedFieldNames.size()); assertTrue(result.containsAll(expectedFieldNames)); }
4. Conclusion
In this short tutorial, we made good use of the Java 8 Stream API and an Introspector instance – to invoke all getters and retrieve a list of null properties.
As usual, the code is available over on GitHub.