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


版权声明:本文为Justin_Can原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。