在项目开发中经常会使用到枚举,下面将举个例子,展示枚举的使用,不说废话,直接上代码。
package com.tom.enumTest; public enum StatusType {
A("FOOD","1"), B("CAR","2"), C("HOME","3");
private String label;
private String value;
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
/**
* @return the value
*/
public String getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
private StatusType(String label, String value) {
this.label = label;
this.value = value;
}
public StatusType getStatusTypeByValue(String val) {
for (StatusType statusType : StatusType.values()) {
if (statusType.getValue().equals(val)) {
return statusType;
}
}
return null;
} }
package com.tom.enumTest; import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; public class TestForEnum {
private static final String GET_LABEL_METHOD = "getLabel";
public static <T extends Enum<T>> T translateByCode(final Class<T> clazz, final String code) {
if(code != null){
try {
final Method m = clazz.getDeclaredMethod(GET_LABEL_METHOD);
for (T t : inspectConstants(clazz)) {
if (code.equals(m.invoke(t))) {
return t;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return null;
}
public static <T extends Enum<T>> List<T> inspectConstants(final Class<T> clazz) {
return new ArrayList<T>(Arrays.asList(clazz.getEnumConstants()));
}
public static void main(String[] args) {
StatusType statusType = translateByCode(StatusType.class, "FOOD");
System.out.println(statusType.getLabel()+","+statusType.getValue());
}
}
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());
}