基本Demo:
/**
* 2018年10月16日上午11:08:01
*/
package testenum;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
/**
* @author XWF
*
*/
public class TestEnum {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(SIMPLE_ENUM.A.getDesc());
System.out.println(SIMPLE_ENUM.getEnumByIndex(2));
System.out.println(SIMPLE_ENUM.getEnumByIndex(3));
System.out.println(SIMPLE_ENUM.getEnumByIndex(5).getDesc());
SIMPLE_ENUM.getEnumByIndex(5).abstractFun();
}
}
enum SIMPLE_ENUM{
A("this is A",2) {
@Override
public void abstractFun() {
System.out.println("a fun");
}
},
B("that is B",5) {
@Override
public void abstractFun() {
System.out.println("b fun");
}
};
private int index;
private String desc;
private SIMPLE_ENUM(String s,int i){
desc = s;
index = i;
}
private static Map<Integer,SIMPLE_ENUM> m = new HashMap<>();
static {
for(SIMPLE_ENUM e:EnumSet.allOf(SIMPLE_ENUM.class)) {
m.put(e.getIndex(), e);
}
}
public int getIndex() {
return index;
}
public String getDesc() {
return desc;
}
public static SIMPLE_ENUM getEnumByIndex(int index) {
return m.get(index);
}
public abstract void abstractFun();
}
结果: