Java枚举中嵌套枚举用例

来源:互联网 发布:网路和网络 编辑:程序博客网 时间:2024/05/18 02:03

最近项目中需要在枚举类中定义枚举常量的子枚举,翻了一下编程思想,顺手写了一个枚举中嵌套枚举的小demo,供各位码友参考。

public enum TestEnum {    LOW(Type.Common.class),    HIGH(Type.Customized.class);  //枚举常量必须写在最前面,否则会报错    interface Type{      //使用interface将子枚举类型组织起来        enum Low implements Type{            FIRST("1","first"),            SECOND("2","second"),            THIRD("3","third"),            FOURTH("4","fourth");            private String code;            private String description;            Common(String code,String desciption){                this.code=code;                this.description=desciption;            }            public String getCode(){                return code;            }            public String getDescription(){                return description;            }        }        enum High implements Type{            FIFTH("5","fifth"),            SIXTH("6","sixth");            private String code;            private String description;            Customized(String code,String desciption){                this.code=code;                this.description=desciption;            }            public String getCode(){                return code;            }            public String getDescription(){                return description;            }        }        String getCode();        String getDescription();    }    public Tuple<TestEnum,Type> get(String channel){        for(TestEnum e:TestEnum.values()){            for(Type t:e.values){                if(t.getCode().equals(channel)){                    return new Tuple<TestEnum, Type>(e,t);                }            }        }        return null;    }    public Type[] getValues(){        return values;    }    Type[] values;    TestEnum(Class<? extends Type> kind){        this.values=kind.getEnumConstants();    }    public static void main(String[] args){        TestEnum e=TestEnum.CUSTOMIZED;        Tuple<TestEnum,Type> tuple=e.get("1");        if(tuple!=null){            System.out.println(tuple.getM().name());            System.out.println(tuple.getT().getCode());        }    }}

这里Tuple是自己写的一个元组封装类,代码如下:

public class Tuple<M,T> {    private final M m;    private final T t;    public Tuple(M m, T t){        this.m = m;        this.t = t;    }    public M getM() {        return m;    }    public T getT() {        return t;    }}

总结:其实枚举嵌套枚举实现方法有多种,不过基本原理都是使用interface把子枚举组织起来。只要掌握了基本思想,形式可以任意变化。

原创粉丝点击