How to access Enum which is inside the class from another project using reflection?

Viewed 46

First of all, I have Enum inside the class e.g. :

public class MyABC
{ 
  String temp = "allow"; 
  .... 
  public enum Steps{ Step1,Step2,Step3 }
  ....
}

Now I want to access Enum -"Steps" from other package, but was not able to find specific method for that.

I am able to find values with below code where class is in given project,

Class<?> myClass = com.....MyABC.Steps.class;
System.out.println(Arrays.asList(myClass.getEnumConstants()));

But I am getting classNotFound when I am using like

   try { 
    Class<?> myclass = Class.forName("com.....MyABC.Steps");
    System.out.println(Arrays.asList(myClass.getEnumConstants())); 

    } catch (Exception e) {
      exception....
   }
1 Answers

Java reflections at runtime deal with compiled code (.class format). Steps enum is an inner class, after building the project, the compiler transforms the inner class name to OuterClass$InnerClass, so to call it with reflection you need to do like below:

Class<?> myclass = Class.forName("com.....MyABC$Steps")

Now it should work.

Related