英文:
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 = "allow";
....
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<?> myClass = com.....MyABC.Steps.class;
System.out.println(Arrays.asList(myClass.getEnumConstants()));
But I am getting classNotFound when I am using like
try {
Class<?> myclass = Class.forName("com.....MyABC.Steps");
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<?> myclass = Class.forName("com.....MyABC$Steps")
Now it should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论