gpt4 book ai didi

java - @Min 字符串验证

转载 作者:行者123 更新时间:2023-12-04 18:01:57 26 4
gpt4 key购买 nike

@Min 的 javadoc (javax.validation.constraints.Min) 中声明只能验证数值。

@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER}) @Retention(value=RUNTIME) @Documented @Constraint(validatedBy={}) public @interface Min

The annotated element must be a number whose value must be higher or equal to the specified minimum.

Supported types are:

BigDecimal
BigInteger
byte, short, int, long, and their respective wrappers

Note that double and float are not supported due to rounding errors (some providers might provide some approximative support)

null elements are considered valid

当我将注解添加到字符串时,它获取字符串的值并将其转换为 BigDecimal,然后检查该值。就好像 String 包含一个 BigDecimal 值。

问题:

  1. 记录在哪里?
  2. 为什么 Eclipse Mars 不接受这个?

查看 Eclipse(编译器)消息:

The javax.validation.constraints.Min constraint supports the following types: java.math.BigDecimal, java.math.BigInteger, byte, short, int, long, and their respective wrapper types.

测试.java

import javax.validation.constraints.Min;

public class Test {
@Min(10)
String quantity;
}

代码按预期工作。

最佳答案

您可能正在使用 Hibernate Validator作为 Bean Validation API 的实现.引用 its documentation :

BigDecimal, BigInteger, byte, short, int, long and the respective wrappers of the primitive types; Additionally supported by HV: any sub-type of CharSequence (the numeric value represented by the char sequence is evaluated), any sub-type of Number

正如您在问题中所说的那样,@Min 的 Bean 验证规范注释不强制实现者支持 String(或 CharSequence)。这只是一个 Hibernate 特性,可能不适用于其他实现。

请注意,在 appendix C of the spec 中, 表示如下:

Persistence Provider should optionally recognize and try to apply the following constraints as well:

  • @Min / @Max on numeric columns (TODO String too?)

关于java - @Min 字符串验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33735477/

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