Java.lang.Enum 类

java.lang.Enum.toString() 方法返回此枚举常量的名称,如声明中所包含的那样。

语法

public String toString() 

参数

无需参数。

返回值

返回此枚举常量的名称。

异常

无。

示例:

在下面的示例中,java.lang.Enum.toString() 方法返回给定枚举的名称。

import java.lang.*;

public class MyClass {
  
  //创建一个枚举
  public enum WeekDay{
    MON("1st"), TUE("2nd"), WED("3rd"), THU("4th"), FRI("5th");

    String day;
    WeekDay(String x) {
      day = x;
    }

    String showDay() {
      return day;
    }
  }

  public static void main(String[] args) {
    System.out.println("WeekDay List:");
    for(WeekDay i : WeekDay.values()) {
      System.out.println(i + " is the " + i.showDay() + " day of the week.");
    }

    WeekDay val = WeekDay.MON;
    System.out.println("WeekDay Name = " + val.toString()); 

  }
} 

上述代码的输出将是:

WeekDay List:
MON is the 1st day of the week.
TUE is the 2nd day of the week.
WED is the 3rd day of the week.
THU is the 4th day of the week.
FRI is the 5th day of the week.
WeekDay Name = MON