来自列表的 Java 验证

标签 java playframework

如果我有一个类,并且我想检查该类中属性的输入是否在列表中,我该怎么做?

示例

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/

相关文章:

database - Playframework 无法在生产环境中读取数据库表?

java - 在hadoop(2.2.0)中使用新的api和工具接口(interface)

java - Play Framework 2.4 : Use Spring Depedency Injection with Play-Framework Instead of Guice

java - 如何将返回值和验证错误传达给方法的调用者?

java - jdeps 相当于 Java 7

javascript - Play框架集成测试中禁用HtmlUnit javascript错误?

json - Play JSON可选转换器

java - 扩展 Play 框架的 GenericModel

java - 从Firebase数据库获取数据时如何准确知道未能转换其值的属性

java - 从用户定义的文件路径访问外部资源 (Java)