Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

Java中的枚举类型存储在Jvm运行期的那个区域?为什么单例模式用枚举就完美解决了?

Java中的枚举类型是存储在Java运行期的那个区域?为什么单例模式用枚举就完美解决了?

枚举的内存分配是发生在什么时候?初始化又是啥发生在什么时候?代码中使用枚举时候,发生了什么事情?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Java中枚举存在在Method Area(方法区)

public enum T {
    E1, E2
}

上面这段代码编译后如下:

$ javap T.class
Compiled from "T.java"
public final class io.zhudy.web.T extends java.lang.Enum<io.zhudy.web.T> {
  public static final io.zhudy.web.T E1;
  public static final io.zhudy.web.T E2;
  public static io.zhudy.web.T[] values();
  public static io.zhudy.web.T valueOf(java.lang.String);
  static {};
}

可以发现常量最后实际都是被编译为静态变量了,Java中静态变量都是存储在Method Area


单例模式的目的是为了保证在内存中只存在唯一一个实例,而枚举值固定的刚好可以达到控制实例数的目的

那传统的采用class实现单例与enum不同之处呢,在于使用使用class需要将constructor访问级别设置为private如果还要防止reflect绕过访问控制创建对象,还需要做额外处理如下:

public class T2 {

    public static final T2 INSTANCE = new T2();

    private T2() {
        if (INSTANCE != null) {
            throw new AssertionError("实例已存在");
        }
    }

    public static void main(String[] args) throws Exception {
        Constructor c = T2.class.getDeclaredConstructor();
        Object o = c.newInstance();
        System.out.println(o);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...