单例实现思路
1、构造方法私有化;2、实例化的变量引用私有化;3、获取实例的方法共有。
Hello.java
public enum Hello {
HELLO;
}
通过 javac Hello.java
javap: 是一个字节码反汇编工具,提供类的结构、方法签名和字节码的详细信息,但不生成源代码。
javap -c Hello >1.txt
Compiled from "Hello.java"
public final class test.Hello extends java.lang.Enum<test.Hello> {
public static final test.Hello HELLO;
public static test.Hello[] values();
Code:
0: getstatic #1 // Field $VALUES:[Ltest/Hello;
3: invokevirtual #2 // Method "[Ltest/Hello;".clone:()Ljava/lang/Object;
6: checkcast #3 // class "[Ltest/Hello;"
9: areturn
public static test.Hello valueOf(java.lang.String);
Code:
0: ldc #4 // class test/Hello
2: aload_0
3: invokestatic #5 // Method java/lang/Enum.valueOf:(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;
6: checkcast #4 // class test/Hello
9: areturn
static {};
Code:
0: new #4 // class test/Hello
3: dup
4: ldc #7 // String HELLO
6: iconst_0
7: invokespecial #8 // Method "<init>":(Ljava/lang/String;I)V
10: putstatic #9 // Field HELLO:Ltest/Hello;
13: iconst_1
14: anewarray #4 // class test/Hello
17: dup
18: iconst_0
19: getstatic #9 // Field HELLO:Ltest/Hello;
22: aastore
23: putstatic #1 // Field $VALUES:[Ltest/Hello;
26: return
}
jad 反编译器,可以将 .class 文件转换为接近源代码的 .java 文件
jad -p Hello.class >result.java 获取的编译后的数据
public final class Hello extends Enum {
public static Hello[] values() {
return (Hello[]) $VALUES.clone();
}
public static Hello valueOf(String s) {
return (Hello) Enum.valueOf(Hello, s);
}
private Hello(String s, int i) {
super(s, i);
}
public static final Hello HELLO;
private static final Hello $VALUES[];
static {
HELLO = new Hello("HELLO", 0);
$VALUES = (new Hello[]{
HELLO
});
}
}