1.项目中对一些相同定义的属性常量定义为枚举进行使用,如下是一个简单的枚举定义:
import java.util.HashMap;
import java.util.Map;
public enum TravelProductType {
FLIGHT("Flights", "机票"),
HOTEL("Hotel", "酒店"),
VACATION("Vacation", "度假"),
TRAIN("Train", "火车票"),
PIAO("Piao", "门票");
private String type;
private String name;
public String getType() {
return type;
}
public String getName() {
return name;
}
private TravelProductType(String type, String name) {
this.type = type;
this.name = name;
}
private static final Map<String, TravelProductType> intToEnum = new HashMap<>();
static {
for (TravelProductType aEnum : TravelProductType.values()) {
intToEnum.put(aEnum.getType(), aEnum);
}
}
public static TravelProductType from(String type) {
return intToEnum.get(type);
}
public static boolean exist(String type) {
return intToEnum.containsKey(type);
}
}
2.使用:
TravelProductType .FLIGHT.getType();
TravelProductType.FLIGHT.getName();
TravelProductType.exist("Flights");
TravelProductType.from("Flights");