在字节码级别,Java';getEnumConstants()知道哪些类是枚举类吗?
Java反射API包含一个方法在字节码级别,Java';getEnumConstants()知道哪些类是枚举类吗?,java,reflection,enums,jvm-bytecode,Java,Reflection,Enums,Jvm Bytecode,Java反射API包含一个方法Class.getEnumConstants(),该方法可以确定类是否是enum类(如果它不认为类是enum,则返回null),以及它的常量是什么 我正在开发一个直接生成JVM字节码的程序,并试图生成一个枚举类。因此,我需要知道Java如何从字节码识别枚举类,以便getEnumConstants能够正常工作。显然,类需要扩展Enum,但这本身显然是不够的(例如,公共类示例扩展Enum{}对应的字节码将不会被识别为Enum);类的JVM字节码还需要具备哪些其他功能,以
Class.getEnumConstants()
,该方法可以确定类是否是enum
类(如果它不认为类是enum
,则返回null
),以及它的常量是什么
我正在开发一个直接生成JVM字节码的程序,并试图生成一个枚举类。因此,我需要知道Java如何从字节码识别枚举类,以便
getEnumConstants
能够正常工作。显然,类需要扩展Enum
,但这本身显然是不够的(例如,公共类示例扩展Enum{}
对应的字节码将不会被识别为Enum
);类的JVM字节码还需要具备哪些其他功能,以便Java的反射API将其识别为Javaenum
,并能够确定其enum常量?为了编译enum
类型,您必须在类的访问标志中用标志标记该类
此外,对于每个常量,您必须创建一个相应的public static final
字段,该字段也在字段的访问标志中标记为
然后,需要一个(名为
的no-argvoid
方法)来创建实例并将它们分配给字段
但这还不够。Mind,它指定两个隐式声明的方法的存在
这是编译人员的职责。字节码生成工具,用于将其实现插入特定枚举类型。请注意,尽管是由编译器生成的,但这两个方法都是
规范没有说明反射将如何收集其信息。它可以遍历标记的字段并读取它们,以组装一个数组,也可以只调用特定类型的
values()
方法。因此,您不能忽略任何这些工件,也不能仅通过委托给类来实现values()
方法。getEnumConstants()
可能会给您一些指针。设置ACC_ENUM
,请参阅
/**
* Returns an array containing the constants of this enum
* type, in the order they're declared. This method may be
* used to iterate over the constants as follows:
*
* for(E c : E.values())
* System.out.println(c);
*
* @return an array containing the constants of this enum
* type, in the order they're declared
*/
public static E[] values();
/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type. (Extraneous whitespace
* characters are not permitted.)
*
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);