如何检查列表中是否初始化了 0 个元素



例如:

public List<Integer> list = new ArrayList<>();

我如何通过反射检查此列表是否为空而不是为空?

for (final Field field : ReflectionUtils.getDeclaredFields(clazz)) {
    if (List.class.isAssignableFrom(field.getType())) {
        // TODO check whether the list is empty.
    }
}

您可以使用Field.get()获取字段值,然后将其转换为List

List<?> l = (List<?>) Field.get(obj);
if (l == null || l.isEmpty()) {
}

您可以使用以下内容来检查天气 它是空的和空的。

public boolean isEmpty() {
    Field fields[] = this.getClass().getDeclaredFields();
    for (Field field : fields) {
        try {
            Object value = field.get(this);
            if (value != null) {
                return false;
            }
        }
        catch (IllegalArgumentException e) {        
            e.printStackTrace();
        }
        catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return true;
}
接口

List中有一个名为isEmpty()的方法。您可以在 if 条件下使用该方法,如下所示。

 if  (list==null||list.isEmpty) {
    //TODO if the list is empty
 }

最新更新