gpt4 book ai didi

java - 如何为枚举实现 JSR-303

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:20 24 4
gpt4 key购买 nike

我正在构建一个 Rest WS 并使用 JSR-303 BeanValidation 来验证请求元素,但有一个字段类型 Enum。

EmploymentType.java

public enum EmploymentType {
EMPTY, FULL, PARTTIME, CONTRACT, CASUAL;

public static EmploymentType getDefaultEnum() {
return EMPTY;
}
}

以及我用来实现此目的的类:

就业.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;
}
}

我开发的实现只能防止枚举成为空对象,有没有办法验证枚举的值仅在声明值的范围内? (空职、全职、兼职、契约(Contract)、休闲)

最佳答案

我相信您必须验证 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();
}
}

关于java - 如何为枚举实现 JSR-303,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46085611/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com