//实现接口,并且以内部类的形式 publicenum Gender implements GenderDesc { // public static final Gender MALE = new Gender("男"); MALE("男") { publicvoidinfo(){ System.out.println("gender male information"); } }, FEMALE("女") {
publicvoidinfo(){ System.out.println("gender female information"); } }; private String name; privateGender(String name){ this.name = name; } } publicclassenumTest{ publicstaticvoidmain(String[] args){ // 通过valueof方法获取指定枚举类的值 Gender gf = Enum.valueOf(Gender.class, "FEMALE"); Gender gm = Enum.valueOf(Gender.class, "MALE"); System.out.println(gf + " is stand for " + gf.getName()); System.out.println(gm + " is stand for " + gm.getName()); gf.info(); gm.info(); } }
枚举实现单例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
package com.bigdata.juc.singleton; /* * 枚举类型:表示该类型的对象是有限的几个 * 我们可以限定为一个,就成了单例 */ enum EnumSingleton{ //等价于 public static final INSTANCE=new EnumSingleton(); INSTANCE } publicclassSingleton2{ publicstaticvoidmain(String[] args){ EnumSingleton s = EnumSingleton.INSTANCE; System.out.println(s); } }
枚举类不会被反射玩坏
1 2 3 4 5 6 7 8 9
public T newInstance(Object ... initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { ... if ((clazz.getModifiers() & Modifier.ENUM) != 0) thrownew IllegalArgumentException("Cannot reflectively create enum objects"); ... }