Java enum valueof has two parameters?

Why does valueof have two parameters?

In Java documentation for valueof

But most of the examples I see online say:

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

Test:

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

It seems that this method only uses one parameter?

Solution

You can check the bytecode to see what happens when compiling enumerations:

public enum TestEnum {A,B}

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'm not an expert on bytecode, but you can see this line:

INVOKESTATIC java/lang/Enum.valueOf (Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;

Actually call Java lang.Enum. valueOf. The Java equivalent looks like this:

public static TestEnum myValueOf(String name) {
    return Enum.valueOf(TestEnum.class,name);
}

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 the two fragments, you can see that the difference is... Yes, name (and line number):

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>