示例:
public enum EnumTest {
FRANK("The given name of me"),
LIU("The family name of me");
private String context;
private String getContext(){
return this.context;
}
private EnumTest(String context){
this.context = context;
}
public static void main(String[] args){
for(EnumTest name :EnumTest.values()){
System.out.println(name+" : "+name.getContext());
}
System.out.println(EnumTest.FRANK.getDeclaringClass());
}
}
Java中枚举实现的分析:
示例:
public enum Color{
RED,BLUE,BLACK,YELLOW,GREEN
}
final enum hr.test.Color {
// 所有的枚举值都是类静态常量
public static final enum hr.test.Color RED;
public static final enum hr.test.Color BLUE;
public static final enum hr.test.Color BLACK;
public static final enum hr.test.Color YELLOW;
public static final enum hr.test.Color GREEN;
private static final synthetic hr.test.Color[] ENUM$VALUES;
// 初始化过程,对枚举类的所有枚举值对象进行第一次初始化
static {
0 new hr.test.Color [1]
3 dup
4 ldc [16] //把枚举值字符串"RED"压入操作数栈
6 iconst_0 // 把整型值0压入操作数栈
7 invokespecial hr.test.Color(java.lang.String, int) [17] //调用Color类的私有构造器创建Color对象RED
10 putstatic hr.test.Color.RED : hr.test.Color [21] //将枚举对象赋给Color的静态常量RED。
......... 枚举对象BLUE等与上同
102 return
};
// 私有构造器,外部不可能动态创建一个枚举类对象(也就是不可能动态创建一个枚举值)。
private Color(java.lang.String arg0, int arg1){
// 调用父类Enum的受保护构造器创建一个枚举对象
3 invokespecial java.lang.Enum(java.lang.String, int) [38]
};
public static hr.test.Color[] values();
// 实现Enum类的抽象方法
public static hr.test.Color valueOf(java.lang.String arg0);
}
enum Color{
RED(255,0,0),BLUE(0,0,255),BLACK(0,0,0),YELLOW(255,255,0),GREEN(0,255,0);
//构造枚举值,比如RED(255,0,0)
private Color(int rv,int gv,int bv){
this.redValue=rv;
this.greenValue=gv;
this.blueValue=bv;
}
public String toString(){ //覆盖了父类Enum的toString()
return super.toString()+"("+redValue+","+greenValue+","+blueValue+")";
}
private int redValue; //自定义数据域,private为了封装。
private int greenValue;
private int blueValue;
}
public static void main(String args[])
{
// Color colors=new Color(100,200,300); //wrong
Color color=Color.RED;
System.out.println(color); // 调用了toString()方法
}
3、所有枚举类都继承了Enum的方法,下面我们详细介绍这些方法。 //JDK源代码:
public final boolean equals(Object other) {
return this==other;
}
Color color=Color.RED;
switch(color){
case RED: System.out.println("it's red");break;
case BLUE: System.out.println("it's blue");break;
case BLACK: System.out.println("it's blue");break;
}