简体   繁体   中英

Returning a value from an enum

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM