您可以使用反射,这样您就不需要单独手动测试每个文件:
static void testAllFieldsForNull(List<Book> bookList) throws IllegalAccessException {
for (int i = 0; i < bookList.size(); i++){
Book book = bookList.get(i);
Field[] fields = book.getClass().getDeclaredFields();
for(Field field: fields){
Class<?> fieldType = field.getType();
if(!fieldType.isPrimitive()){
if (field.get(book) == null){
System.out.println("Field [" + field.getName() + "] has null value for book at position " + i);
continue;
}
if(fieldType.isAssignableFrom(String.class) && ((String)field.get(book)).isEmpty()){
System.out.println("Field [" + field.getName() + "] is empty String for book at position " + i);
}
}
}
}
}
测试:
public static void main(String[] args) throws IllegalAccessException {
Book b = new Book(1, "", "Ok");
Book c = new Book(2, "Z", "");
Book d = new Book(0, "C", null);
List<Book> x = new ArrayList<>();
x.add(b);
x.add(c);
x.add(d);
testAllFieldsForNull(x);
}
输出:
Field [name] is empty String for book at position 0
Field [author] is empty String for book at position 1
Field [author] has null value for book at position 2
或者,如果您只需要收集“好”书籍(实际上是任何类型的物品),您可以使用:
public static boolean testObject(Object obj){
Field[] fields = obj.getClass().getDeclaredFields();
boolean okay = true;
for(Field field: fields){
Class<?> fieldType = field.getType();
try{
if(!fieldType.isPrimitive()){
if (field.get(obj) == null){
okay = false;
continue;
}
if(fieldType.isAssignableFrom(String.class) && ((String)field.get(obj)).isEmpty()){
okay = false;
}
}
}catch (IllegalAccessException e){
e.printStackTrace();
return false;
}
}
return okay;
}
然后将其用于过滤:
public static void main(String[] args) throws IllegalAccessException {
Book b = new Book(1, "", "Ok");
Book c = new Book(2, "Z", "");
Book d = new Book(0, "C", null);
Book a = new Book(3, "C", "D");
List<Book> x = new ArrayList<>();
x.add(b);
x.add(c);
x.add(d);
x.add(a);
System.out.println(
x
.stream()
.filter(FieldTest::testObject)
.collect(Collectors.toList()).get(0).id
);
}