简体   繁体   English

枚举在类中时的Java枚举反射

[英]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 (ie FirstClass, SecondClass, etc.) and pull the enum (always called "EnumGroup") out and call the method getName() on each value of the enum. 我的目标是以编程方式迭代这些类(即FirstClass,SecondClass等)并拉出枚举(总称为“EnumGroup”)并在枚举的每个值上调用方法getName()。

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. 我看过这篇关于Java反射和枚举的StackOverflow帖子 ,但是当我尝试通过指定路径(com.package.FirstClass.EnumGroup)来获取我的枚举时,我得到了一个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. 我不一定需要这个设置,但最终目标是在每个迭代enum的类中都没有相同的代码。

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 $ . 由于您使用Class.forName你需要使用类的名称 ,并在类名内类型从外类型的分离$

So use 所以使用

Class<?> clz = Class.forName("com.package.FirstClass$EnumGroup");
//                                                  ^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM