从Java中的枚举获取字符串值


76

我有一个像这样定义的枚举,我希望能够获取各个状态的字符串。我应该如何写这样的方法?

我可以获取状态的int值,但也希望从int中获取字符串值。

public enum Status {
    PAUSE(0),
    START(1),
    STOP(2);

    private final int value;

    private Status(int value) {
        this.value = value
    }

    public int getValue() {
        return value;
    }
}

7
状态s = Status.PAUSE; System.out.println(s.name());
Nikola Yovchev


2
除了定义0,1,2,您还可以使用Status.ordinal();
Arnaud Denoyelle

2
@ArnaudDenoyelle:您应该避免使用ordinal(),请参见Joshua Bloch的“有效Java”
GarfieldKlon

1
@GarfieldKlon我同意。我不(也永远不会)建议依靠,ordinal()因为在枚举中添加值会改变每个枚举的序数。我想指出,OP复制了ordinal()的行为。
2015年

Answers:


112

如果statusStatusenum类型,status.name()将为您提供其定义的名称。


3
toString()根据官方文档,@ JoeMaher似乎是首选的方式:“大多数程序员应该优先使用toString()方法,因为toString方法可能返回更用户友好的名称。” (docs.oracle.com/javase/6/docs/api/java/lang/Enum.html#name()
卡斯滕·

7
status.name()如果要在代码中使用@Carsten,则适用(出于准确性和一致性);status.toString()如果要向用户显示,则@Carsten适用(出于可读性)。
intcreator

50

您可以使用values()方法:

例如,Status.values()[0]在您的情况下将返回PAUSE,如果您toString()将其打印,将被调用并打印“ PAUSE”。


是的,只是要添加Status.values()[0]的类型Status不是String
2013年

13

使用给定的波纹管使用默认方法name()

public enum Category {
        ONE("one"),
        TWO ("two"),
        THREE("three");

        private final String name;

        Category(String s) {
            name = s;
        }

    }

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Category.ONE.name());
    }
}

1
为什么不重写toString以返回名称?
Mohammed Housseyn Taleb'1

4
返回什么?一个或一个,有一个区别(枚举名称或其值)
Mercury

9

您可以将此方法添加到您的Status枚举中:

 public static String getStringValueFromInt(int i) {
     for (Status status : Status.values()) {
         if (status.getValue() == i) {
             return status.toString();
         }
     }
     // throw an IllegalArgumentException or return null
     throw new IllegalArgumentException("the given number doesn't match any Status.");
 }

public static void main(String[] args) {
    System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}

0

我相信枚举在其API中有一个.name(),使用起来非常简单,例如以下示例:

private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }

    private enum Security {
            low,
            high
    }

有了这个你可以简单地打电话

yourObject.security() 

在此示例中,它返回高/低作为字符串

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.