如何匹配Java枚举

San*_*kar 2 java enums

我有一个这样的枚举:

public enum ChartType
{   
    TABLE(0, false), BAR(1, false), COLUMN(3, false)
    private int type;
    private boolean stacked;
    ChartType(int type, boolean stacked)
    {
        this.type = type;
        this.stacked = stacked;
    }
    public int getType()
    {
        return type;
    }
    public boolean isStacked()
    {
        return this.stacked;
    }
}
Run Code Online (Sandbox Code Playgroud)

我从请求中获取了一个图表类型(int值,如0、1、3),并希望有匹配的输入

use*_*041 5

遵循这些原则。不知道语法是否是100%,但是它演示了这个想法。

public ChartType getChartypeForValue(int value)
    for(ChartType type : ChartType.values()){
        if(type.getType()  == value){
            return type;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)


Psh*_*emo 5

您可以在枚举中添加地图以存储type和特定枚举值之间的关系。在创建所有值后,您可以在静态块中填充一次,例如:

private static Map<Integer, ChartType> typeMap = new HashMap<>();

static{
    for (ChartType chartType: values()){
        typeMap.put(chartType.type, chartType);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以添加方法,该方法将使用此映射来获取您想要的值,如果没有,则为 null

public static ChartType getByType(int type) {
    return typeMap.get(type);
}
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它

ChartType element = ChartType.getByType(1);
Run Code Online (Sandbox Code Playgroud)