gpt4 book ai didi

java - 我可以覆盖 jsr-303 验证注释吗

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:08:56 25 4
gpt4 key购买 nike

我有如下测试:

public class TestSizeAnnotation
{
public static void main(String[] args)
{
System.out.println(Validation.buildDefaultValidatorFactory().getValidator().validate(new C()));
}

public static class P
{
private List<String> lst = newArrayList("AA");
@Size(max=0, message="P")
public List<String> getLst()
{
return lst;
}

public void setLst(List<String> lst)
{
this.lst = lst;
}
}

public static class C extends P
{
@Override
@Size(max=5, message="C")
public List<String> getLst()
{
return super.getLst();
}
}
}

输出如下:
[ConstraintViolationImpl{interpolatedMessage='P', propertyPath=lst, rootBeanClass=class com....validator.TestSizeAnnotation$C, messageTemplate='P'}]

不过,我希望注解可以覆盖@Size,不会出现警告。
有没有办法做到这一点?

编辑:我找到了一个 bug似乎与此有关,但我运行 4.2.0 final 仍然得到上述行为。

最佳答案

JSR-303 实际上不支持覆盖验证注解。相反,子类中重写方法的注解将累积地应用:来自规范的第 3.3 节:

A constraint declaration can be placed on an interface. For a given class,constraint declarations held on super- classes as well as interfaces areevaluated by the Bean Validation provider. Rules are formally described inSection 3.4.5.The effect of constraint declarations is cumulative. Constraints declaredon a superclass getter will be validated along with any constraints definedon an overridden version of the getter according to the Java LanguageSpecification visibility rules.

关于java - 我可以覆盖 jsr-303 验证注释吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9067420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com