您可以将unknown或default或invalid值添加到您的枚举中,如果它是null或empty space将被映射
package com.test;
import java.util.HashMap;
public class Brand{
private static HashMap map = new HashMap();
public enum BrandName {
HERO("hero"),HONDA("honda"),UNKNOWN("default");
private String value = null;
private BrandName(String value){
this.value = value;
addToMap();
}
private void addToMap(){
map.put(this.value, this);
}
@Override
public String toString(){
return this.value;
}
public static BrandName fromValue(String value){
return map.get(value) != null ? map.get(value) : map.get("default");
}
}
}使用fromValue方法,您可以从值获取枚举对象。
使用toString方法,您可以获得枚举对象的值。
map将包含枚举对象映射的值。如果地图中不存在null或empty space等值,则地图将返回null,在这种情况下,方法fromValue将返回UNKNOWN枚举对象。
System.out.println(Brand.BrandName.HERO.toString());
System.out.println(Brand.BrandName.fromValue("").toString());
System.out.println(Brand.BrandName.fromValue(null).toString());
System.out.println(Brand.BrandName.fromValue("honda").toString());