描述
本文先反编译枚举,再使用枚举实现单例
枚举
public enum EnumDemo {
RED("red"),BLUE("blue"),PURPLE("purple");
private String dest;
EnumDemo(String dest) {
this.dest = dest;
}
public static void getColor() {
return;
}
}
java -jar cfr-0.146.jar EnumDemo.class --sugarenums false
/*
* Decompiled with CFR 0.146.
*/
package com.redoor.singleton;
public final class EnumDemo
extends Enum<EnumDemo> {
public static final /* enum */ EnumDemo RED = new EnumDemo("RED", 0, "red");
public static final /* enum */ EnumDemo BLUE = new EnumDemo("BLUE", 1, "blue");
public static final /* enum */ EnumDemo PURPLE = new EnumDemo("PURPLE", 2, "purple");
private String dest;
private static final /* synthetic */ EnumDemo[] $VALUES;
public static EnumDemo[] values() {
return (EnumDemo[])$VALUES.clone();
}
public static EnumDemo valueOf(String name) {
return Enum.valueOf(EnumDemo.class, name);
}
private EnumDemo(String string, int n, String dest) {
super(string, n);
this.dest = dest;
}
static {
$VALUES = new EnumDemo[]{RED, BLUE, PURPLE};
}
}
单例
单例源码
public enum Singleton {
INSTANCE;
private final Student student;
Singleton() {
student = new Student();
}
private Student getStudent() {
return student;
}
public static Student getInstance() {
return Singleton.INSTANCE.getStudent();
}
}
单例反编译
java -jar cfr-0.146.jar Singleton.class --sugarenums false
/*
* Decompiled with CFR 0.146.
*
* Could not load the following classes:
* com.redoor.singleton.Student
*/
package com.redoor.singleton;
import com.redoor.singleton.Student;
public final class Singleton
extends Enum<Singleton> {
public static final /* enum */ Singleton INSTANCE = new Singleton("INSTANCE", 0);
private final Student student = new Student();
private static final /* synthetic */ Singleton[] $VALUES;
public static Singleton[] values() {
return (Singleton[])$VALUES.clone();
}
public static Singleton valueOf(String name) {
return Enum.valueOf(Singleton.class, name);
}
private Singleton(String string, int n) {
super(string, n);
}
private Student getStudent() {
return this.student;
}
public static Student getInstance() {
return INSTANCE.getStudent();
}
static {
$VALUES = new Singleton[]{INSTANCE};
}
}
引用
http://www.benf.org/other/cfr/how-are-enums-implemented.html
http://www.jetchen.cn/java-singleton-enum/
网友评论