与 anyMatch 不兼容返回并尝试/捕获异常

我在 java 8 中有这个通用方法。这个方法获取数组列表,并且对于这个列表中的每个元素获取对象中的所有字段,以验证任何值是否为 null 或空字符串

我有这个错误

不兼容的类型。找到:'void',需要:'boolean'

代码:

public boolean nullFieldCreated() {
        return ((ArrayList) object).forEach(obj ->
                Arrays.stream(obj.getclass().getDeclaredFields())
                        .filter(field -> (field.getName() != "id" && field.getName() != "cardId"))
                        .anyMatch(fieldValue -> {
                            try {
                                return fieldValue.get(obj) == null || fieldValue.get(obj).equals(EMPTY);
                            } catch (IllegalaccessException e) {
                                e.printStackTrace();
                            }
                            return false;
                        }));
}

对于这个对象:

{

"trainingList": [
    {
        "id": "","startDate": "","duration": "","topic": "","trainingTypeId": "","trainingPlaceId": ""
    }
],"driverLicenseList": [
    {
        "id": "","date": "","classDriverLicenseId": ""
    }
] }

该方法获取任何不指定类型的对象,objectifs 检测此对象中声明的所有属性并验证是否有任何一个为 null 或为空,如果是则返回 true 或 false

使用方法:

if (!new NullField(request.getTrainingList()).nullFieldCreated())) 
    do something;
else
    do other;
freepear 回答:与 anyMatch 不兼容返回并尝试/捕获异常

您的代码不起作用,因为 forEach 是一个空函数。你可以像这样修复它:

public boolean nullFieldCreated() {
    boolean result = false;

    for (Object obj : object) {
      result =
          Arrays.stream(obj.getClass().getDeclaredFields())
              .filter(field -> (field.getName() != "id" && field.getName() != "cardId"))
              .anyMatch(
                  fieldValue -> {
                    try {
                      return fieldValue.get(obj) == null || fieldValue.get(obj).equals(EMPTY);
                    } catch (IllegalAccessException e) {
                      e.printStackTrace();
                    }
                    return false;
                  });
      if (result) break;
    }
    
    return result;
  }
本文链接:https://www.f2er.com/3284.html

大家都在问