3

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.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 2
    Don't think of `enum` types as special. They end up just being classes. They're reference types like any other. `Object` is their super type. – Sotirios Delimanolis Jun 19 '14 at 17:56
  • The answer depends on how the enums are organized. Are they top-level classes, or members of some other class? You are right about reflection, though. That is the only way to do it. – Chronio Jun 19 '14 at 17:56

1 Answers1

2

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)

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • You can also use [`isAssignableFrom`](http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#isAssignableFrom-java.lang.Class-) – adarshr Jun 19 '14 at 18:00
  • 1
    Please note there may not be a standard and simple way to go over all loaded classes. Especially so when you don't already know how the classes are loaded (IDEs, the Java plugin for browsers, and the java executable could load classes all in different ways, for example). – Chronio Jun 19 '14 at 18:21