4

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.

3
  • Hi @JBNizet - added the line that throws the ClassNotFoundException. Commented Oct 19, 2015 at 18:40
  • Why use Class.forName()? Why not simply use the class literal com.package.FirstClass.EnumGroup.class? You wouldn't have the exception, the compiler would check that you're using a valid class name, and refactoring would automatically make your code correct. Commented Oct 19, 2015 at 18:45
  • Can down-voters explain why this question isn't good or up to their standards? Thanks! Commented Oct 19, 2015 at 21:12

1 Answer 1

14

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");
//                                                  ^
Sign up to request clarification or add additional context in comments.

1 Comment

Amazingly fast and correct answer. Thanks @Pshemo! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.