将枚举中的所有名称作为String [] [英] Getting all names in an enum as a String[]

查看:84
本文介绍了将枚举中的所有名称作为String []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将枚举元素的名称作为 String s的数组获得最简单和/或最短的方法?

What's the easiest and/or shortest way possible to get the names of enum elements as an array of Strings?

我的意思是,例如,如果我有以下枚举:

What I mean by this is that if, for example, I had the following enum:

public enum State {
    NEW,
    RUNNABLE,
    BLOCKED,
    WAITING,
    TIMED_WAITING,
    TERMINATED;

    public static String[] names() {
        // ...
    }
}

names()方法会将数组模拟返回到 {NEW RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED}

the names() method would return an array analog to { "NEW", "RUNNABLE", "BLOCKED", "WAITING", "TIMED_WAITING", "TERMINATED" }.

推荐答案

更新:



在java 8中,使用流的任意枚举类是一行:

Update:

In java 8, it's one line for an arbitrary enum class using a stream:

public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.stream(e.getEnumConstants()).map(Enum::name).toArray(String[]::new);
}

在java 7中,有点不太优雅,但这个一行技巧:

In java 7, a bit less elegant, but this one-liner does the trick:

public static String[] names() {
    return Arrays.toString(State.values()).replaceAll("^.|.$", "").split(", ");
}

此外,这里有一个版本可用于任何枚举:

Also, here's a version of this that will work for any enum:

public static String[] getNames(Class<? extends Enum<?>> e) {
    return Arrays.toString(e.getEnumConstants()).replaceAll("^.|.$", "").split(", ");
}

你会这样称呼:

String[] names = getNames(State.class); // any other enum class will work too

这篇关于将枚举中的所有名称作为String []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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