You can just examine the bytecode to see what happens when an enum
is compiled:
public enum TestEnum {A, B}
And the bytecode of valueOf
:
// access flags 0x9
public static valueOf(Ljava/lang/String;)LTestEnum;
L0
LINENUMBER 1 L0
LDC LTestEnum;.class
ALOAD 0
INVOKESTATIC java/lang/Enum.valueOf (Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
CHECKCAST TestEnum
ARETURN
L1
LOCALVARIABLE name Ljava/lang/String; L0 L1 0
MAXSTACK = 2
MAXLOCALS = 1
I am no expert in byte code but you can see that the line:
INVOKESTATIC java/lang/Enum.valueOf (Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
In fact invokes java.lang.Enum.valueOf
. A java equivalent would look like this:
public static TestEnum myValueOf(String name) {
return Enum.valueOf(TestEnum.class, name);
}
And the bytecode confirms this:
// access flags 0x9
public static myValueOf(Ljava/lang/String;)LTestEnum;
L0
LINENUMBER 6 L0
LDC LTestEnum;.class
ALOAD 0
INVOKESTATIC java/lang/Enum.valueOf (Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
CHECKCAST TestEnum
ARETURN
L1
LOCALVARIABLE name Ljava/lang/String; L0 L1 0
MAXSTACK = 2
MAXLOCALS = 1
Comparing these two snippets you can see the difference is... yes, the name (and the line number):
