Alexander Mills
Alexander Mills

Reputation: 100000

Iterating through declared enums in Java

Say I want to iterate through all declared enum classes that implement a certain interface.

So I have:

enum Fruit implements Edible {

//etc

}

enum Vegetable implements Edible {

//etc

}

enum Candy implements Edible {

//etc

}

is there a way in Java to loop through all the enum classes that implement the Edible interface? I assume this would require reflection. With standard Java classes, I don't believe there is a way to do this (to find all classes that subclass a certain type, or find all classes that implement a certain interface) but with enums, there should be a way to do this in Java.

Upvotes: 3

Views: 108

Answers (1)

Jigar Joshi
Jigar Joshi

Reputation: 240880

scan through all classes in classpath and check if isEnum() and check if getInterfaces() contains Editable.class or check Editable.class.isAssignableFrom(ClassToCheck) (as pointed out in comments)

Upvotes: 2

Related Questions