Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum reflection when enum is inside a class

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.

like image 905
Mark Avatar asked Dec 11 '22 20:12

Mark


1 Answers

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");
//                                                  ^
like image 66
Pshemo Avatar answered Dec 27 '22 00:12

Pshemo