Java枚举中嵌套枚举用例

最近项目中需要在枚举类中定义枚举常量的子枚举,翻了一下编程思想,顺手写了一个枚举中嵌套枚举的小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把子枚举组织起来。只要掌握了基本思想,形式可以任意变化。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值