List of enum values in java

后端 未结 6 852
甜味超标
甜味超标 2021-02-01 01:25

Is it possible to create ArrayList of enum values (and manipulate it)? For example:

enum MyEnum
{
   ONE, TWO
}

MyEnum my = MyEnum.ONE;
List  al = new          


        
6条回答
  •  佛祖请我去吃肉
    2021-02-01 01:48

    This is a more generic solution, that can be use for any Enum object, so be free of used.

    static public List constFromEnumToList(Class enumType) {
        List nueva = new ArrayList();
        if (enumType.isEnum()) {
            try {
                Class cls = Class.forName(enumType.getCanonicalName());
                Object[] consts = cls.getEnumConstants();
                nueva.addAll(Arrays.asList(consts));
            } catch (ClassNotFoundException e) {
                System.out.println("No se localizo la clase");
            }
        }
        return nueva;
    }
    
    
    

    Now you must call this way:

    constFromEnumToList(MiEnum.class);
    

    提交回复
    热议问题