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

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

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

问题

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

  1. public class MyABC
  2. {
  3. String temp = "allow";
  4. ....
  5. public enum Steps{ Step1,Step2,Step3 }
  6. ....
  7. }

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

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

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

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

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

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

  1. public class MyABC
  2. {
  3. String temp = &quot;allow&quot;;
  4. ....
  5. public enum Steps{ Step1,Step2,Step3 }
  6. ....
  7. }

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,

  1. Class&lt;?&gt; myClass = com.....MyABC.Steps.class;
  2. System.out.println(Arrays.asList(myClass.getEnumConstants()));

But I am getting classNotFound when I am using like

  1. try {
  2. Class&lt;?&gt; myclass = Class.forName(&quot;com.....MyABC.Steps&quot;);
  3. System.out.println(Arrays.asList(myClass.getEnumConstants()));
  4. } catch (Exception e) {
  5. exception....
  6. }

答案1

得分: 3

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

  1. 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:

  1. 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:

确定