Skip to content
Advertisement

How to iterate through several Enums within a class

I have a class with 70 enums. I would like to iterate through the enums and just output the constants saved in each enum. it looks like this:

public class A {
    public enum One{
        ABC, DEF,
    }
    . 
    .
    .
    public enum Seventy{
        ASAS, SDDSDS,
    }
}
 

I found a similar question here. But the question and suggested solutions are for 3 enums only. Is there an easier way than just hardcoding each enum’s name into an array? Maybe there’s already a java solution, like getAllMethods() that I dont know of??

Advertisement

Answer

        Arrays.stream(A.class.getDeclaredClasses()).forEach(e ->
            Arrays.stream(e.getDeclaredFields())
                    .filter(Field::isEnumConstant)
                    .forEach(System.out::println));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement