Simple use of Java Enum
- 2020-09-28 08:53:40
- OfStack
Recently, in order to parse the description information of the status code, I learned the use of Enum in 1, and found it is quite useful.
First, the class Status, which defines an Enum, has two attributes statusValue status code and statusDesc status description
public enum Status {
STATUS_OK("01"," successful "),
STATUS_FAILED("02"," failure "),
STATUS_NOTHING("03"," An unknown state ");
private Status(String statusValue, String statusDesc){
this.statusValue = statusValue;
this.statusDesc = statusDesc;
}
// through statusValue Fetch status description
public static String getStatusDesc(String statusValue){
for(Status s : Status.values()){
if(s.statusValue.equals(statusValue)){
return s.statusDesc;
}
}
return null;
}
// rewrite toString methods
@Override
public String toString(){
return "statusValue=" + this.statusValue + ",statusDesc=" + this.statusDesc;
}
private String statusValue;// The status value
private String statusDesc;// State description
public String getStatusValue() {
return statusValue;
}
public void setStatusValue(String statusValue) {
this.statusValue = statusValue;
}
public String getStatusDesc() {
return statusDesc;
}
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
}
Test the following
public class App {
public static void main( String[] args )
{
System.out.println(Status.getStatusDesc("01"));// Output: Success
System.out.println(Status.STATUS_FAILED.getStatusDesc());// Output: Failed
System.out.println(Status.STATUS_NOTHING.toString());// Output: statusValue=03,statusDesc= An unknown state
}
}