Enum内部実装解析
2546 ワード
簡単にEnumタイプを書き、逆コンパイルします.
逆コンパイル後のソースコードは次のとおりです.
逆コンパイルのソースコードを見て、大体わかるでしょう.java 1.5時に加わる多くの特性は、実はすべてコンパイル時期に加えられたもので、JVM内部で実現するのは変わっていません.例えば、汎用型もそうです.興味があるのは自分で逆コンパイルして汎用型の実現をすることができますが、汎用型の実現は確かにコンパイル時期に操作が複雑で、thinking in javaで説明されています.全体的に、私にとって、enumタイプの応用は比較的に少なく、文章を読む時にいくつか理解しただけなので、記録して、プロジェクトの中で後で深く応用するのに役立ちます.
/**
*
* @author zhxing
* @since 2010.02.26
*/
public enum Test{
// ,
Spring("a"),Summer("b",1),Autumn("c"),Winter("d");
//
public static int staticValue=10;
//
private String s;
private int value;
//
Test(String s){
this.s=s;
}
Test(String s,int value){
this.s=s;
this.value=value;
}
//
public int getValue() {
return value;
}
public static void main(String[] args) {
System.out.println(Test.valueOf("Spring"));
System.out.println(Test.Spring.s);
}
}
逆コンパイル後のソースコードは次のとおりです.
// Decompiled by DJ v3.9.9.91 Copyright 2005 Atanas Neshkov Date: 2010-2-26 16:07:52
// Home Page : http://members.fortunecity.com/neshkov/dj.html - Check often for new version!
// Decompiler options: packimports(3)
// Source File Name: Test.java
import java.io.PrintStream;
public final class Test extends Enum
{
public static Test[] values()
{
return (Test[])$VALUES.clone();
}
public static Test valueOf(String s1)
{
return (Test)Enum.valueOf(Test, s1);
}
private Test(String s1, int i, String s2)
{
super(s1, i);
s = s2;
}
private Test(String s1, int i, String s2, int j)
{
super(s1, i);
s = s2;
value = j;
}
public int getValue()
{
return value;
}
public static void main(String args[])
{
System.out.println(valueOf("Spring"));
System.out.println(Spring.s);
}
public static final Test Spring;
public static final Test Summer;
public static final Test Autumn;
public static final Test Winter;
public static int staticValue = 10;
private String s;
private int value;
private static final Test $VALUES[];
static
{
Spring = new Test("Spring", 0, "a");
Summer = new Test("Summer", 1, "b", 1);
Autumn = new Test("Autumn", 2, "c");
Winter = new Test("Winter", 3, "d");
$VALUES = (new Test[] {
Spring, Summer, Autumn, Winter
});
}
}
逆コンパイルのソースコードを見て、大体わかるでしょう.java 1.5時に加わる多くの特性は、実はすべてコンパイル時期に加えられたもので、JVM内部で実現するのは変わっていません.例えば、汎用型もそうです.興味があるのは自分で逆コンパイルして汎用型の実現をすることができますが、汎用型の実現は確かにコンパイル時期に操作が複雑で、thinking in javaで説明されています.全体的に、私にとって、enumタイプの応用は比較的に少なく、文章を読む時にいくつか理解しただけなので、記録して、プロジェクトの中で後で深く応用するのに役立ちます.