enum 内部实现解析

  简单写个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
        });
    }
}

 

  看了反编译的源码后,应该知道大概了吧。。在java1.5 时加入的很多特性,其实都是在编译时期加的,在JVM内部实现是没有变的,例如泛型也是这样的,有兴趣的可以自己反编译下泛型的实现,不过泛型的实现确实在编译时期操作比较复杂,在thinking in java 里有讲解到。总体来说,对于我而已,对enum 类型应用比较少,只是在看文章的时候了解了一些,所以记录下,在项目中有助于以后的深入应用。

你可能感兴趣的:(java基础)