Java中枚举嵌套子枚举

本文详细探讨了Java编程中如何使用枚举类型进行嵌套,创建子枚举的概念,包括枚举的定义、嵌套方式、访问权限以及在实际应用中的示例,帮助读者深入理解枚举的高级用法。
public enum TestEnum2 {
	LOW(TestEnum2.Type.Low.class),
	HIGH(TestEnum2.Type.High.class);  //枚举常量必须写在最前面,否则会报错

	private Class<? extends TestEnum2.Type> kind;

	public Type[] getValues(){
		return values;
	}

	Type[] values;

	TestEnum2(Class<? extends TestEnum2.Type> kind) {
		this.kind = kind;
		this.values=kind.getEnumConstants();
	}

	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;
			Low(String code,String desciption){
				this.code=code;
				this.description=desciption;
			}
			@Override
			public String getCode(){
				return code;
			}
			@Override
			public String getDescription(){
				return description;
			}
		}
		enum High implements Type{
			FIFTH("5","fifth"),
			SIXTH("6","sixth");
			private String code;
			private String description;
			High(String code,String desciption){
				this.code=code;
				this.description=desciption;
			}
			@Override
			public String getCode(){
				return code;
			}
			@Override
			public String getDescription(){
				return description;
			}
		}
		String getCode();
		String getDescription();
	}

	public Tuple<TestEnum2,Type> get(String channel){
		for (Type t : this.values) {
			if (t.getCode().equals(channel)) {
				return new Tuple<TestEnum2, Type>(this, t);
			}
		}
		return null;
	}

	public static void main(String[] args){
		TestEnum2 e = TestEnum2.LOW;
		Tuple<TestEnum2,Type> tuple=e.get("1");
		if(tuple!=null){
			System.out.println(tuple.getM().name());
			System.out.println(tuple.getT().getCode());
		}
	}
}

输出结果:

LOW
1

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值