java Enum valueOf has two parameters?

Code_Control_jxie0755 :

Why does valueOf have two parameters?

in Java documentation for valueOf

public static <T extends Enum<T>> T valueOf​(Class<T> enumType, String name)

Parameters:

enumType - the Class object of the enum type from which to return a constant

name - the name of the constant to return

But most examples I read online says:

enum WorkDays {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;
}

Test:

WorkDays day1 = WorkDays.valueOf("MONDAY");
System.out.println(day1); // >>>  MONDAY

It seems that the method used only one parameter?

Lino :

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):

enter image description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89220&siteId=1