Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all enums in my project

Tags:

java

enums

In my project I have a few declared enums. I would like to create a method that loops over all of these and then over all the values of each enum.

Example with two enums:

public enum Mood {
    GOOD, BAD;  
}

public enum Weather {
   WET, DRY;
}

If I looped over each enum and their values and printed them each on a line, the program would print

GOOD
BAD
WET
DRY

The order is not important...

If I add a new enum, that should also be printed without having to change the code. I cannot know in what package the enums will be located. Only a root package.

like image 665
Ludwig Magnusson Avatar asked Nov 16 '25 11:11

Ludwig Magnusson


1 Answers

The Reflections library will help you.

You can search for each class which implements Enum and get all the classes values using clazz.getEnumConstants()

like image 117
Peter Lawrey Avatar answered Nov 18 '25 06:11

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!