Getting all names in an enum as a String[]

前端 未结 21 1369
执笔经年
执笔经年 2020-12-01 03:50

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,

21条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 04:37

    My solution, with manipulation of strings (not the fastest, but is compact):

    public enum State {
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
    
        public static String[] names() {
            String valuesStr = Arrays.toString(State.values());
            return valuesStr.substring(1, valuesStr.length()-1).replace(" ", "").split(",");
        }
    }
    

提交回复
热议问题