Finding an enumeration class using Reflection in Java

I think I need help finding an enum class in another class using reflection in Java. I fought for too long with this. I read this, as well as a number of other posts, and all of them make me think that it should work, as shown below.

public class ModelActivity {
  public enum AttributeEnumeration { MODELID, MODELURGENCY, MODELDUEDATEANDTIME }

  public static void main(String[] args) {
    // Find the class with the given name
    String className = "ModelActivity";
    Class modelClass = null;
    try {
      // Retrieve the Class with the given className...
      modelClass = Class.forName(className);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Class by name '" + className + "' not found.", e);
    }

    // Find the AttributeEnumeration within the class
    String attributeEnumerationClassName = className + ".AttributeEnumeration";
    Class attributeEnumerationClass = null;
    try {
      attributeEnumerationClass = Class.forName(attributeEnumerationClassName);
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Class by name '" + attributeEnumerationClassName + "' not found.", e);
    }
  }
}

However, what actually happens is that modelClass was found correctly, but the EnumerationClass attribute is not, that is, I get a second ClassNotFoundException as follows:

Exception in thread "main" java.lang.RuntimeException: Class by name 'ModelActivity.AttributeEnumeration' not found.
at ModelActivity.main(ModelActivity.java:27)
  Caused by: java.lang.ClassNotFoundException: ModelActivity.AttributeEnumeration
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at ModelActivity.main(ModelActivity.java:25)

Can anyone point out a possibly obvious mistake. Thank.

+5
source share
1 answer

See for yourself:

package foo.bar;

public class Outer{

    public enum Inner{}

    public static void main(final String[] args){
        System.out.println(Inner.class.getName());
    }

}

Conclusion:

foo.bar.Outer $ Inner

$, , ModelActivity$AttributeEnumeration.

BTW:

$ . :

import foo.bar.Outer.Inner;
// ...
private Inner myEnumValue;

:

private foo.bar.Outer.Inner myEnumValue;

, :

assertEquals( // two ways to reference the same class
    foo.bar.Outer.Inner.class,
    Class.forName("foo.bar.Outer$Inner")
);
+10

All Articles