java - 内存分配 Java 枚举

标签 java enums

这个问题是关于枚举内部的对象的内存分配, 我有一个枚举类如下

 class TemplateEnum{

    F1(new Class1()), F2(new Class2()),F3(new Class3());
     /*
        Related code like constructors
     */
   }

我的疑问是何时为类 class1,class2,class3 创建对象(分配内存)。

谢谢

最佳答案

假设你的意思是

enum TemplateEnum {
    F1(new Class1()), F2(new Class2()),F3(new Class3());
    /*
    Related code like constructors
    */
}

JLS指出

In addition to the members that an enum type E inherits from Enum, for each declared enum constant with the name n, the enum type has an implicitly declared public static final field named n of type E. These fields are considered to be declared in the same order as the corresponding enum constants, before any static fields explicitly declared in the enum type. Each such field is initialized to the enum constant that corresponds to it.

因此F1(和其他)变成

public static final TemplateEnum F1 = new TemplateEnum(new Class1()); 

And since static fields are initialized when the class is loaded ,然后将执行每个字段的构造函数调用中的new Class1()

关于java - 内存分配 Java 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297061/

相关文章:

java - 从哪里获得 Flex - Java DS (Blaze) 培训 Material ?

java - 为什么枚举可以有包私有(private)构造函数?

java - 如何在泛型方法中获取枚举类?

将字符串转换为枚举并传入结构

java - 在 JAVA 中检查 ENUM 值与 String 的相等性

java - Swing 组件加载时间太长?

java - 不确定我在这里做错了什么( boolean 标志)

Java Swing : GUI frozen - jstack interpretation

java - 在 Map Reduce 中计算数据集的线性回归

java - 如何用 Java 中的枚举替换旧版标志和常量按位运算?