[英]Why the java method Enum.valueof invoke the enum type constructor?
I have built this kind of data enum: 我已经构建了这种数据枚举:
enum Sexo {
HOMBRE("H"), MUJER("M"), OTRO("O");
private String sexo;
private Sexo(String sexo){
System.out.println("constructor del tipo enum");
this.sexo=sexo;
}
}
Then, in the Main method i just do this: 然后,在Main方法中我只是这样做:
public static void main(String[] args) {
Sexo sexo1 = Enum.valueOf(Sexo.class, "HOMBRE");
Sexo sexo2 = Enum.valueOf(Sexo.class, "MUJER");
Sexo.valueOf("OTRO");
}
then, i have this on the console: 然后,我在控制台上有这个:
constructor del tipo enum
constructor del tipo enum
constructor del tipo enum
i understand that i have a call to the constructor for each enum type whit the sentence "Sexo" (name of the enum type). 据我所知,我对每个枚举类型的构造函数都调用了一个句子“Sexo”(枚举类型的名称)。 But: why the constructor is running just once? 但是:为什么构造函数只运行一次? note that i have two instances and one direct call to the class. 请注意,我有两个实例和一个直接调用该类。
It isnt the method valueOf
that calls the constructor. 它不是调用构造函数的方法valueOf
。
The constructor of an enum
is called for every literal when the class is first used. 首次使用类时,将为每个文字调用enum
的构造函数。 So in your case thats before the first call to Enum.valueOf
. 所以在你的情况下,在第一次调用Enum.valueOf
。
The three calls to the constructor are caused by the three literals not your three calls to valueOf
. 对构造函数的三次调用是由三个文字而不是三次调用valueOf
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.