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);
}
}
The above code is compiled as follows:
You can find that constants are actually compiled into static variables in the end. Static variables in Java are stored in
Method Area
.