I have multiple instances of classes that have a single enum nested inside them. Here is a simplified version of said class:
public class FirstClass extends BaseClass {
public enum EnumGroup {
ONE("one"),
TWO("two");
private String mName;
EnumGroup(String name) {
this.mName = name;
}
public String getName() {
return mName;
}
}
// FirstClass methods
}
My goal is to programmatically iterate over these classes (i.e. FirstClass, SecondClass, etc.) and pull the enum (always called "EnumGroup") out and call the method getName() on each value of the enum.
I've looked at this StackOverflow post on Java reflection and enums, but when I try to fetch my enum by specifying the path (com.package.FirstClass.EnumGroup) I get a ClassNotFoundException. I'm guessing putting the enum inside the class is messing something up.
Class<?> clz = Class.forName("com.package.FirstClass.EnumGroup");
I don't necessarily need this set-up, but the end goal is not have the same code in each class that iterates over the enum.
Since you are using Class.forName
you need to use name of class, and in class names inner types are separated from outer types with $
.
So use
Class<?> clz = Class.forName("com.package.FirstClass$EnumGroup");
// ^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With