如何使用反射访问位于另一个项目中的类内部的枚举?

huangapple go评论55阅读模式
英文:

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

问题

首先,我在类内部有一个枚举类型,例如:

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

现在我想从其他包访问枚举类型 "Steps",但是没有找到特定的方法。

我可以使用以下代码在给定项目中的类中找到枚举值:

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

但是,当我使用以下方式时,我会得到 "classNotFound" 错误:

try {
  Class<?> myclass = Class.forName("com.....MyABC.Steps");
  System.out.println(Arrays.asList(myClass.getEnumConstants()));
} catch (Exception e) {
  异常处理....
}
英文:

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

public class MyABC
{ 
  String temp = &quot;allow&quot;; 
  .... 
  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&lt;?&gt; myClass = com.....MyABC.Steps.class;
System.out.println(Arrays.asList(myClass.getEnumConstants()));

But I am getting classNotFound when I am using like

   try { 
    Class&lt;?&gt; myclass = Class.forName(&quot;com.....MyABC.Steps&quot;);
    System.out.println(Arrays.asList(myClass.getEnumConstants())); 

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

答案1

得分: 3

Java运行时的反射处理编译后的代码(.class格式)。
Steps枚举是一个内部类,在构建项目后,编译器将内部类名称转换为OuterClass$InnerClass,因此要使用反射调用它,您需要像下面这样做:

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

现在应该可以正常工作。

英文:

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&lt;?&gt; myclass = Class.forName(&quot;com.....MyABC$Steps&quot;)

Now it should work.

huangapple
  • 本文由 发表于 2020年9月14日 22:48:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63886689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定