Java 有没有办法限制POJO中字符串的大小,并在超出限制时引发特定异常?

Java 有没有办法限制POJO中字符串的大小,并在超出限制时引发特定异常?,java,Java,我需要一个快速的解决方案来限制属性,使其具有特定的限制,如果超过限制,则抛出一个自定义异常,类似于注释,用于指定要抛出的限制和异常。Java8中有类似的吗 例如: @Size(max=20, ex=CustomEx, msg= "Exced the limit") private String myAttribute; 一种简单的方法是将验证代码放在setter中: public void setMyAttribute(String value) throws CustomEx { i

我需要一个快速的解决方案来限制属性,使其具有特定的限制,如果超过限制,则抛出一个自定义异常,类似于注释,用于指定要抛出的限制和异常。Java8中有类似的吗

例如:

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

一种简单的方法是将验证代码放在setter中:

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);
}

一种简单的方法是将验证代码放在setter中:

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);
}

标准方法是使用运行此测试的setter来执行此操作。Java不会为您这样做(但请参见以下内容:)
public void setMyAttribute(String value){if(null!=value&&value.length()>20).
标准方法是使用运行此测试的setter执行此操作。Java不会为您执行此操作(但请参见:)。
public void setMyAttribute(String value){if(null!=value&&value.length()>20)…
如果对象是从包含所有参数的构造函数中创建的,那么构造函数可以调用内部setter方法来执行验证。这实际上是使Pojo不可变并在构造函数中执行所有操作的一个选项-根本不需要setter方法。如果对象是从构造函数中创建的,则然后你的构造函数可以调用内部setter方法来执行验证。这实际上是一个使你的Pojo不可变并在构造函数中执行所有操作的选项-根本不需要setter方法。