Java.lang.Enum 类

java.lang.Enum.clone() 方法用于抛出 CloneNotSupportedException。这保证了枚举永远不会被克隆,这是保持其"单例"状态所必需的。

语法

protected final Object clone()
                      throws CloneNotSupportedException

参数

不需要参数.

返回值

此方法不返回任何值。

异常

抛出CloneNotSupportedException,如果对象的类不支持 Cloneable 接口。重写clone方法的子类也可以抛出此异常,以指示实例无法克隆。

示例:

在下面的示例中,如果给定的对象等于给定的枚举常量,则 java.lang.Enum.clone() 方法返回 true。

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("Enums can never be cloned:");
    MyClass e = new MyClass() {
      protected final Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
      }
    }; 

    System.out.println("WeekDay List:");
    for(WeekDay i : WeekDay.values()) {
      System.out.println(i + " is the " + i.showDay() + " day of the week.");
    }
  }
}

上述代码的输出将是:

Enums can never be cloned:
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.