Enum e = SexTwo.MALE;Class clazz = e.getDeclaringClass();if(clazz.isEnum()){ SexTwo[] constants = (SexTwo[]) clazz.getEnumConstants();}潍坊IT培训负责整理
枚举使用抽象方法
前面提到了枚举类型编译之后是以 class 方式运行的,因此枚举类型也可以定义抽象方法.有同学可能要问了,前面说是 final class 类型,怎么可以定义抽象方法呢,抽象方法需要类型是 abstract class ?我们来试一下.
如下,SexThree 定义了一个抽象方法 getAlias().枚举值 MALE 实现了这个抽象方法,返回 "man".在枚举中定义抽象方法,可以为多个枚举值定义不同的实现,枚举值自身即可处理数据.

enum SexThree { MALE { String getAlias() { return "man"; } }; abstract String getAlias();}
对 SexThree 进行编译和反编译,可以看到,这里生成的类型是抽象类,仍然继承了 Enum.MALE 在编译后生成了 SexThree$1.class,继承 SexThree 并实现了抽象方法.虽然这里枚举类型是抽象类,但是 java 编译器限制了我们不能继承这个抽象类,继承情况下编译时会报错"枚举类型不可继承".
abstract class SexThree extends Enum { public static SexThree[] values() { return (SexThree[])$VALUES.clone(); } public static SexThree valueOf(String s) { return (SexThree)Enum.valueOf(test/SexThree, s); } private SexThree(String s, int i) { super(s, i); } abstract String getAlias(); public static final SexThree MALE; private static final SexThree $VALUES[]; static { MALE = new SexThree("MALE", 0) { String getAlias() { return "man"; } }; $VALUES = (new SexThree[] { MALE }); }}
枚举实现接口
枚举最终编译成 class,因此也可以实现接口.如下的 SexFour 就实现了 Runnable 接口,定义了 run 方法.因为枚举不能继承其他类型,这个特性使得我们可以通过实现多个方法来定义枚举的某些特征.
enum SexFour implements Runnable { ; public void run() { //something }}
对 SexFour 进行编译和反编译,可以看到,这里又生成了 final class 类型,并且继承了 Enum,实现了 Runnable 接口.
final class SexFour extends Enum implements Runnable{ public static SexFour[] values(){ return (SexFour[])$VALUES.clone(); } public static SexFour valueOf(String s){ return (SexFour)Enum.valueOf(test/SexFour, s); } private SexFour(String s, int i){ super(s, i); } public void run(){ } private static final SexFour $VALUES[] = new SexFour[0];}
以上就是潍坊IT培训给大家做的内容详解,更多关于IT的学习,请继续关注潍坊IT培训