1. Overview
1.概述
In this quick article, we’ll use the Java 8 Stream API and the Introspector class – to invoke all getters found in a POJO.
在这篇快速文章中,我们将使用Java 8 Stream API和Introspector类–来调用在POJO中发现的所有getters。
We will create a stream of getters, inspect return values and see if a field value is null.
我们将创建一个获取器流,检查返回值并查看一个字段的值是否为null.。
2. Setup
2.设置
The only setup we need is to create a simple POJO class:
我们需要的唯一设置是创建一个简单的POJO类。
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
// standard getters and setters
}
3. Invoking Getter Methods
3.调用获取器方法
We’ll analyze the Customer class using Introspector; this provides an easy way for discovering properties, events, and methods supported by a target class.
我们将使用Introspector来分析Customer类;这为发现目标类所支持的属性、事件和方法提供了一种简单的方法。
We’ll first collect all the PropertyDescriptor instances of our Customer class. PropertyDescriptor captures all the info of a Java Bean property:
我们首先要收集我们的Customer类的所有PropertyDescriptor实例。PropertyDescriptor 捕获了一个 Java Bean 属性的所有信息。
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:
现在让我们去看看所有的PropertyDescriptor实例,并为每个属性调用读取方法。
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:
我们在上面使用的nulls 谓词检查属性是否可以被读取,调用getter并只过滤空值。
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:
最后,让我们现在创建一个Customer的实例,将一些属性设置为null并测试我们的实现。
@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
4.结论
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.
在这个简短的教程中,我们很好地利用了Java 8 Stream API和一个Introspector 实例–来调用所有的getters并检索一个空属性列表。
As usual, the code is available over on GitHub.
像往常一样,代码可以在GitHub上找到。