Java根据枚举值获取枚举名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3889248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:25:05  来源:igfitidea点击:

Java getting the Enum name given the Enum Value

javaenumsenumeration

提问by Julia

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

给定值,如何获取 Java Enum 类型的名称?

I have the following code which works for a particularEnum type, can I make it more generic?

我有以下代码适用于特定的Enum 类型,我可以让它更通用吗?

public enum Category {

    APPLE("3"), 
    ORANGE("1"), 

    private final String identifier;

    private Category(String identifier) {
        this.identifier = identifier;
    }

    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.equalsIgnoreCase(value)) {
                return eachValue.name();
            }
        }
        return enumValue;
    }
}

回答by Riduidel

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

您应该getEnumNameForValue通过调用该name()方法来替换您的。

回答by prashant thakre

Try below code

试试下面的代码

public enum SalaryHeadMasterEnum {

    BASIC_PAY("basic pay"),
    MEDICAL_ALLOWANCE("Medical Allowance");

    private String name;

    private SalaryHeadMasterEnum(String stringVal) {
        name=stringVal;
    }
    public String toString(){
        return name;
    }

    public static String getEnumByString(String code){
        for(SalaryHeadMasterEnum e : SalaryHeadMasterEnum.values()){
            if(e.name.equals(code)) return e.name();
        }
        return null;
    }
}

Now you can use below code to retrieve the Enum by Value

现在您可以使用以下代码按值检索枚举

SalaryHeadMasterEnum.getEnumByString("Basic Pay")

Use Below code to get ENUM as String

使用下面的代码将 ENUM 作为字符串

SalaryHeadMasterEnum.BASIC_PAY.name()

Use below code to get string Value for enum

使用下面的代码获取枚举的字符串值

SalaryHeadMasterEnum.BASIC_PAY.toString()

回答by Javaci

Try, the following code..

试试,下面的代码..

    @Override
    public String toString() {
    return this.name();
    }

回答by Do It

Here is the below code, it will return the Enum name from Enum value.

这是下面的代码,它将从 Enum 值返回 Enum 名称。

public enum Test {

    PLUS("Plus One"), MINUS("MinusTwo"), TIMES("MultiplyByFour"), DIVIDE(
            "DivideByZero");
    private String operationName;

    private Test(final String operationName) {
        setOperationName(operationName);
    }

    public String getOperationName() {
        return operationName;
    }

    public void setOperationName(final String operationName) {
        this.operationName = operationName;
    }

    public static Test getOperationName(final String operationName) {

        for (Test oprname : Test.values()) {
            if (operationName.equals(oprname.toString())) {
                return oprname;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return operationName;
    }
}

public class Main {
    public static void main(String[] args) {

        Test test = Test.getOperationName("Plus One");
        switch (test) {
        case PLUS:
            System.out.println("Plus.....");
            break;
        case MINUS:
            System.out.println("Minus.....");
            break;

        default:
            System.out.println("Nothing..");
            break;
        }
    }
}

回答by Ankit

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

在这种情况下,您可以将 enum 的值转换为 List 并通过它进行流式处理。类似于下面的例子。我建议使用filter()

Using ForEach:

使用 ForEach

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

或者,使用过滤器

When you want to find with code:

当你想用代码查找时:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

当你想用名字查找时:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

希望能帮助到你!我知道这是一个很老的帖子,但有人可以得到帮助。