在Java中找不到类型的枚举常量 [英] No Enum constant found for type in java

查看:575
本文介绍了在Java中找不到类型的枚举常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中使用 enum ,这是枚举

I am using enum in java, Here is the enum

public enum AbuseSectionType{

    MUSIC("Music"), DANCE("Dance"), SOLO("Solo"), ACT("Act")

    private String displayString;

    AbuseSectionType(String displayValue) {
        this.displayString = displayValue;
    }

    @JsonValue
    public String getDisplayString() {
        return displayString;
    }

    public void setDisplayString(String displayString) {
        this.displayString = displayString;
    }
}

我正在尝试获取价值 AbuseSectionType.valueOf( Music)。我没有枚举常量,也没有发现错误。我应该具有值 MUSIC

I am trying to get value AbuseSectionType.valueOf("Music"). I am getting no enum constant and found no error. I am supposed to have value MUSIC.

推荐答案

<$ c枚举的$ c> name()是声明时指定的名称,在您的情况下为 MUSIC

The name() of an enum is the name specified when declaring it, MUSIC in your case.

如果我们阅读 valueOf()的javadoc:

If we read the javadoc for valueOf():


使用
指定的名称返回指定枚举类型的枚举常量。

Returns the enum constant of the specified enum type with the specified name.

valueOf ()使用枚举的 name()。但是您想要实现的目标是不同的,因此您不能使用此方法。相反,您可以做的是使自己的方法从您自己的字段( displayString )中查找值。

valueOf() is using the name() of the enum. But what you want to achieve is different, so you cannot use this method. What you can do instead is to make your own method that finds the value from your own field (displayString).

下面是一个示例:

public static AbuseSectionType fromDisplayString(String displayString)
{
    for(AbuseSectionType type : AbuseSectionType.values())
        if(type.getDisplayString().equals(displayString)
            return type;

    return null; //not found
}

这篇关于在Java中找不到类型的枚举常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆