使用Java中的Reflection查找枚举类

时间:2011-01-03 08:23:11

标签: java reflection enums

我认为我需要一些帮助,在Java中使用反射在另一个类中查找枚举类。我一直在和这个争斗太久了。我已经阅读了这个以及其他一些帖子,他们都让我相信它应该如下工作。

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);
    }
  }
}

然而,实际发生的是找到了modelClass,但是attributeEnumerationClass却没有,也就是说,我得到了第二个ClassNotFoundException,如下所示:

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)

有人可以指出 - 可能很明显 - 错误给我。谢谢。

1 个答案:

答案 0 :(得分:10)

亲眼看看:

package foo.bar;

public class Outer{

    public enum Inner{}

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

}

输出:

  

foo.bar.Outer $内

内部类名用$分隔,而不是句号分隔,所以你需要ModelActivity$AttributeEnumeration

顺便说一句:

$语法仅对类加载有效。使用句点来访问源中类的实例,如下所示:

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")
);