Issue
public class test{
private String id;
private String status;
private Integer alertsCount
}
I have a class test, when a rest api implemented using springboot with post request gets triggered input json looks like
{
"id": "1",
"status": "Cancelled",
"alertCount": 10
}
at my model class i need to add restriction to prevent status to be one of the below values "Successfull", "Cancelled", "In Progress", "On Hold"
How can i achieve this.
Solution
Since status
field has to have value from predefined set of constants, it would be better to provide an enum containing all available status strings.
public class TestModel{
private String id;
private StatusEnum status;
private Integer alertsCount;
}
public enum StatusEnum {
SUCCESSFUL("Successful"),
CANCELLED("Cancelled"),
IN_PROGRESS("In progress"),
ON_HOLD("On hold");
private String statusTag;
StatusEnum(String status){
this.statusTag = status;
}
}
Enums are designed for exactly such situations, according to Java documentation (https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html):
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.
Answered By - maslosh
Answer Checked By - Terry (JavaFixing Volunteer)