我在我的应用程序中为自定义数据类型创建了一些自定义 bean 类,例如 Address
, PhoneNumber
, SpecialCode
等
这些自定义的非原始数据类型 有自己的限制,我想对它们应用这些限制,例如考虑 PhoneNumber
:
public class PhoneNumber {
private String stdCode;
private String number;
public PhoneNumber() {
}
public PhoneNumber(String stdCode, String number) {
this.stdCode = stdCode;
this.number = number;
}
/* getters and setters */
}
现在让我感到困惑的是 PhoneNumber
上的限制 ,即,我想确保 stdCode
必须以 0
开头,或 number
必须是 7
或 8
数字长等
那么,这些规则应该在哪里应用呢?
在构造函数中?作为:
//Custom costructor
public PhoneNumber(String stdCode, String number) {
if (!stdCode.matches("[0-9]+") || !number.matches("[0-9]+")){
throw new IllegalArgumentException("Error in Parsing. The STD Code and Number MUST be numeric digits.");
}
if (!"0".equals(stdCode.substring(1, 2))){
throw new IllegalArgumentException("The STD Code must begins with 0");
}
if (stdCode.length() < 3 || stdCode.length() > 5){
throw new IllegalArgumentException("The STD Code must be 3 to 5 digits long. Current Number of digits: " + stdCode.length() + ". ");
}
this.stdCode = stdCode;
this.number = number;
}
或者也可以有自定义异常(exception)?我应该在哪里将这些自定义异常与我的 bean 类合并?
我不是一个经验丰富的程序员,想知道我应该在这里应用什么设计模式?
最佳答案
你应该为你的手机 # 部分创建 getters 和 setters 并在 setters 中验证检查
关于java - 处理 bean 类中的自定义限制/异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10804250/