如果我有一个类,并且我想检查该类中属性的输入是否在列表中,我该怎么做?
示例
public class Length {
public static final List<String> ALLOWABLE_UNITS =
Collections.unmodifiableList(Arrays.asList("inches", "feet", "meters", "millimeters"));
public BigDecimal lengthValue;
@SomeMatchingAnnotation(ALLOWABLE_UNITS)
public String lengthUnit;
}
是否有注释可以做到这一点?我必须创建自己的吗?
最佳答案
在您的字段的 setter 中,您可以像这样进行验证:
public void setLengthUnit(String lengthUnit) {
if (!ALLOWABLE_UNITS.contains(lengthUnit) {
throw new IllegalArgumentException("Length unit not recognized.");
}
this.lengthUnit = lengthUnit;
}
关于来自列表的 Java 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24727176/