有什么方法可以限制POJO中字符串的大小,并在超出限制时抛出特定异常?

时间:2019-05-09 01:31:03

标签: java

我需要一种快速的解决方案来限制具有特定限制的属性,如果超出限制,则抛出自定义异常(如注释),以指定要抛出的限制和异常。 Java 8中有类似的东西吗?

示例:

@Size(max=20, ex=CustomEx, msg= "Exced the limit")
private String myAttribute;

1 个答案:

答案 0 :(得分:1)

一种简单的方法是将您的验证代码放入设置器中:

public void setMyAttribute(String value) throws CustomEx {
    if (value != null && value.length() > 20) {
        throw new CustomEx("Exceeded the limit");
    }

    myAttribute = value;
}

编辑:使用构造函数时的验证:

public MyClass(String value) throws CustomEx {  // the constructor
    setMyAttribute(value);
}