Returning a value from an enum

user2254180 :

I have the following enum, it contains label and field values. I would like to return the field by passing in the label name.

Can anyone make any suggestions?

public enum Table (
   NAME("name", "FULL_NAME");

   public final String label;
   public final String field;

   private Table(String label, String field) {
   this.label = label;
   this.field = field;
   }
}
Michael Gantman :

Add method getField to your enum

public enum Table (
   NAME("name", "FULL_NAME");

   public final String label;
   public final String field;

   private Table(String label, String field) {
   this.label = label;
   this.field = field;
   }

   public static String getField(String label) {
     String result = null;
     for(Table t : Table.values()) {
       if(t.label.equals(label) {
         result = t.field;
         break;
       }
     }
     return result;
   }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216285&siteId=1