我正在构建一个Rest WS并验证我正在使用JSR-303 BeanValidation的请求元素,但是有一个字段类型Enum。
EmploymentType.java
public enum EmploymentType {
EMPTY, FULL, PARTTIME, CONTRACT, CASUAL;
public static EmploymentType getDefaultEnum() {
return EMPTY;
}
}
和我用来实现这个的类:
Employment.java
public class Employment implements Serializable{
private static final long serialVersionUID = 1L;
@NotNull(message="employmentType does not accept null values")
private EmploymentType employmentType;
@Valid
@NotNull(message="orgData does not accept null values")
private OrgData orgData;
public Employment() {
employmentType = EmploymentType.getDefaultEnum();
orgData = new OrgData();
}
public EmploymentType getEmploymentType() {
return employmentType;
}
public void setEmploymentType(EmploymentType employmentType) {
this.employmentType = employmentType;
}
public OrgData getOrgData() {
return orgData;
}
public void setOrgData(OrgData orgData) {
this.orgData = orgData;
}
}
我开发的实现只能阻止枚举为空对象,有没有办法验证枚举的值是否只在声明值的范围内? (空,全,合同,合同,休闲)
答案 0 :(得分:0)
我相信你必须验证valueOf或枚举的名称 以下是将验证发生的摘录
public class Employment implements Serializable {
@NotNull(message = "employmentType does not accept null values")
@Valid
private EmploymentType employmentType;
public EmploymentType getEmploymentType() {
getEmploymentTypeOfEnum();
return employmentType;
}
@Pattern(regexp = "EMPTY|FULL")
private String getEmploymentTypeOfEnum(){ // you don't need it to be public
return employmentType.name();
}
}