Home  >  Q&A  >  body text

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

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

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

PHP中文网PHP中文网2743 days ago590

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:52:17

    Enumerations in Java exist in Method Area(method area)

    public enum T {
        E1, E2
    }

    The above code is compiled as follows:

    $ 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 {};
    }

    You can find that constants are actually compiled into static variables in the end. Static variables in Java are stored in Method Area.


    单例模式的目的是为了保证在内存中只存在唯一一个实例,而枚举值 is fixed just enough to achieve the purpose of controlling the number of instances

    The traditional method of bypassing access controlclass实现单例与enum不同之处呢,在于使用使用class需要将constructor访问级别设置为private如果还要防止reflectcreating objects requires additional processing as follows:

    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);
        }
    }

    reply
    0
  • Cancelreply