「Java]java.lang.Enum.clone()メソッドを使うサンプル
java.lang.Enum.clone()説明
enumが複製されないことを保証します。「シングルトン」ステータスを保持するために必要です。
Javaコード
package com.arkgame.study;
public class LangEnumDemo {
//enum definition
enum User {
AA(21), BB(25);
int age;
User(int p) {
age = p;
}
int showAge() {
return age;
}
}
@SuppressWarnings("unused")
public static void main(String[] args) {
System.out.println("Enums can never be cloned");
LangEnumDemo tt = new LangEnumDemo() {
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
};
System.out.println("Enums list");
for (User m : User.values()) {
System.out.println(m + " age " + m.showAge() + " 1111");
}
}
}
package com.arkgame.study;
public class LangEnumDemo {
//enum definition
enum User {
AA(21), BB(25);
int age;
User(int p) {
age = p;
}
int showAge() {
return age;
}
}
@SuppressWarnings("unused")
public static void main(String[] args) {
System.out.println("Enums can never be cloned");
LangEnumDemo tt = new LangEnumDemo() {
protected final Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
};
System.out.println("Enums list");
for (User m : User.values()) {
System.out.println(m + " age " + m.showAge() + " 1111");
}
}
}
package com.arkgame.study; public class LangEnumDemo { //enum definition enum User { AA(21), BB(25); int age; User(int p) { age = p; } int showAge() { return age; } } @SuppressWarnings("unused") public static void main(String[] args) { System.out.println("Enums can never be cloned"); LangEnumDemo tt = new LangEnumDemo() { protected final Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }; System.out.println("Enums list"); for (User m : User.values()) { System.out.println(m + " age " + m.showAge() + " 1111"); } } }
結果
Enums can never be cloned
Enums list
AA age 21 1111
BB age 25 1111