【问题标题】:Index of an invalid object within a list列表中无效对象的索引
【发布时间】:2020-11-26 08:46:31
【问题描述】:

Oval 验证框架中是否有与getPropertyPath 方法等效的方法?

下面的示例代码打印对象的所有嵌套无效值的属性。我还想在列表中打印无效对象的索引,但我不确定如何在 Oval 中完成。

使用 javax.validation,我可以调用 ConstraintViolation#getPropertyPath,但在 Oval 中似乎没有等效项。我错过了什么吗?

输出是

list[].value: example.ValidationDemo$Child.value cannot be null
list[].value: example.ValidationDemo$Child.value cannot be null

代码如下:

package example;

import java.util.List;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.constraint.AssertValid;
import net.sf.oval.constraint.NotNull;
import net.sf.oval.context.FieldContext;

public class ValidationDemo {
    public static void main(String[] args) {
        Validator validator = new Validator();
        validator.validate(new Parent())
                .forEach(ValidationDemo::printViolation);
    }

    private static void printViolation(ConstraintViolation violation) {
        printViolation(violation, "");
    }

    private static void printViolation(ConstraintViolation violation, String property) {
        FieldContext fieldContext = (FieldContext) violation.getContext();

        if (!property.isEmpty()) {
            property += ".";
        }

        property += fieldContext.getField().getName();

        if (List.class.isAssignableFrom(fieldContext.getField().getType())) {
            property += "[]"; // How do I find the index of violation.getInvalidValue() within the list?
        }

        if (violation.getCauses() == null) {
            System.out.format("%s: %s\n", property, violation.getMessage());
        } else {
            for (ConstraintViolation cause : violation.getCauses()) {
                printViolation(cause, property);
            }
        }
    }

    public static class Parent {
        @AssertValid
        public final List<Child> list = List.of(new Child("value"),
                new Child(null), new Child(null));
    }

    public static class Child {
        @NotNull
        public final String value;

        public Child(String value) {
            this.value = value;
        }
    }
}

【问题讨论】:

    标签: oval


    【解决方案1】:

    目前这是不可能的。需要扩展此 code part 以跟踪索引。

    【讨论】:

      【解决方案2】:

      ConstraintViolation.getContextPath() 被添加到3.1.0

      【讨论】:

        猜你喜欢
        • 2016-05-01
        • 2016-08-04
        • 1970-01-01
        • 2017-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-26
        相关资源
        最近更新 更多