2017-09-06 82 views
1

我正在構建Rest WS並驗證請求元素我正在使用JSR-303 BeanValidation,但有一個字段類型枚舉。如何爲枚舉實現JSR-303

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

我只開發了防止枚舉作爲一個實施空對象,有沒有辦法來驗證枚舉的值只在聲明值的範圍內? (空,滿,PARTTIME,合同CASUAL)

+3

什麼否則會是?如果某件事設法產生一個類的_valid_實例(帶有一個非空的'employmentType'),那麼它必須具有其中的一個值。這就是枚舉的工作方式...... – user2478398

回答

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