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把子枚举组织起来。只要掌握了基本思想,形式可以任意变化。
阅读全文
0 0
- Java枚举中嵌套枚举用例
- Java中使用枚举
- java中枚举
- java中使用枚举
- java中枚举
- java中枚举举例说明
- java 中使用枚举
- java中枚举
- java中枚举类型
- 19---java中枚举02(枚举)
- 学习笔记:Java 分类枚举和策略枚举(枚举的嵌套)
- java中枚举实现单例模式
- 枚举多层循环嵌套
- Java 枚举单例
- Java枚举单例
- JAVA 中枚举类注意事项
- Java中枚举的使用方法
- JAVA中枚举的优点
- c++ winpcap开发(1)
- linuxrhel6.5虚拟机封装
- Spring AOP动态代理原理与实现方式
- Python特殊语法:filter、map、lambda、reduce
- java继承基本概念练习
- Java枚举中嵌套枚举用例
- windbg 调试bug
- CSS Sprite 学习笔记
- CADisplayLink翻译
- PAT 1001. A+B Format (20)
- Dynamic Memory and Smart Poniters(I)
- 虚拟机的封装
- 【win8.1】安全删除系统盘下的隐藏文件hiblefil.sys
- HDU 2897(邂逅明下) 巴什博弈扩展