繁体   English   中英

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

[英]Getting String value from enum in Java

我有一个这样定义的枚举,我希望能够获得各个状态的字符串。 我该怎么写这样的方法?

我可以获取状态的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;
    }
}

如果statusStatus enum,则status.name()将为您提供其定义的名称。

您可以使用values()方法:

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

使用默认方法名称()作为给定的波纹管

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());
    }
}

您可以将此方法添加到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
}

我相信枚举在其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() 

并且它在此示例中以String返回高/低

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM