获取Enum值的Java获得枚举值 [英] Java getting the Enum name given the Enum Value

查看:2776
本文介绍了获取Enum值的Java获得枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我已经编写了适用于特定枚举类型的代码,可以让它更多通用?



枚举类型:

  public enum Category {

APPLE(3),
ORANGE(1),
GRAPE(GRAPE),
BANANA(Banana);

private final String identifier;

/ **
*构造函数。
*
* @param identifier
* - identfier。
* /
private类别(String identifier){
this.identifier = identifier;
}

/ **
* {@inheritDoc}
* /
public String toString(){
return identifier;
}

public static String getEnumNameForValue(Object value){
Category [] values = Category.values();
String enumValue = null;
for(Category eachValue:values){
enumValue = eachValue.toString();

if(enumValue.equals(value)){
return eachValue.name();
}
}
return enumValue;
}
}


解决方案

你应该通过调用 getEnumNameForValue .html#name()rel =noreferrer> name() 方法。


How do I get the name of a Java Enum type given its value?

I have written code which works for a particular Enum type, can I make it more generic?

The enum type:

public enum Category {

    APPLE("3"), 
    ORANGE("1"), 
    GRAPE("GRAPE"), 
    BANANA("Banana");

    private final String identifier;

    /**
     * Constructor.
     *
     * @param identifier
     *            - identfier.
     */
    private Category(String identifier) {
        this.identifier = identifier;
    }

    /**
     * {@inheritDoc}
     */
    public String toString() {
        return identifier;
    }

    public static String getEnumNameForValue(Object value){
        Category[] values = Category.values();
        String enumValue = null;
        for(Category eachValue : values) {
            enumValue =eachValue.toString();

            if (enumValue.equals(value)) {
                return eachValue.name();
            }
        }
    return enumValue;
    }
}

解决方案

You should replace your getEnumNameForValue by a call to the name() method.

这篇关于获取Enum值的Java获得枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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