在项目开发中经常会使用到枚举,下面将举个例子,展示枚举的使用,不说废话,直接上代码。
1 package com.tom.enumTest; 2 3 public enum StatusType { 4 A("FOOD","1"), B("CAR","2"), C("HOME","3"); 5 private String label; 6 private String value; 7 /** 8 * @return the label 9 */ 10 public String getLabel() { 11 return label; 12 } 13 /** 14 * @param label the label to set 15 */ 16 public void setLabel(String label) { 17 this.label = label; 18 } 19 /** 20 * @return the value 21 */ 22 public String getValue() { 23 return value; 24 } 25 /** 26 * @param value the value to set 27 */ 28 public void setValue(String value) { 29 this.value = value; 30 } 31 private StatusType(String label, String value) { 32 this.label = label; 33 this.value = value; 34 } 35 public StatusType getStatusTypeByValue(String val) { 36 for (StatusType statusType : StatusType.values()) { 37 if (statusType.getValue().equals(val)) { 38 return statusType; 39 } 40 } 41 return null; 42 } 43 44 }
1 package com.tom.enumTest; 2 3 import java.lang.reflect.Method; 4 import java.util.ArrayList; 5 import java.util.Arrays; 6 import java.util.List; 7 8 public class TestForEnum { 9 private static final String GET_LABEL_METHOD = "getLabel"; 10 public static <T extends Enum<T>> T translateByCode(final Class<T> clazz, final String code) { 11 if(code != null){ 12 try { 13 final Method m = clazz.getDeclaredMethod(GET_LABEL_METHOD); 14 for (T t : inspectConstants(clazz)) { 15 if (code.equals(m.invoke(t))) { 16 return t; 17 } 18 } 19 } catch (Exception e) { 20 throw new RuntimeException(e); 21 } 22 } 23 return null; 24 } 25 public static <T extends Enum<T>> List<T> inspectConstants(final Class<T> clazz) { 26 return new ArrayList<T>(Arrays.asList(clazz.getEnumConstants())); 27 } 28 public static void main(String[] args) { 29 StatusType statusType = translateByCode(StatusType.class, "FOOD"); 30 System.out.println(statusType.getLabel()+","+statusType.getValue()); 31 } 32 }
public enum NumberEnum {
ONE("1","哈哈"),
TWO("2","嘿嘿"),
THREE("3","呵呵");
private String key;
private String value;
NumberEnum(String key,String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
public static NumberEnum getByKey(String key){
NumberEnum[] numEnum = NumberEnum.values();
for(NumberEnum dEnum : numEnum){
if(redEnum.getValue() == key){
return dEnum;
}
}
return null;
}
@Test
public void getIt4() {
Map<String,Object> map = new HashMap<String, Object>();
NumberEnum[] numEnum = NumberEnum.values();
if ( null != numEnum && numEnum.length >=0) {
for (NumberEnum nEnum : numEnum) {
map.put(nEnum.getKey(),nEnum.getValue());
}
}
System.out.println(map.size());
}