Java 中的分层枚举
2022-09-04 03:17:57
你可以用这样的技巧来做到这一点:
public interface GROUPMAIN1 {
enum SUBGROUP1 implements GROUPMAIN1 {
COL1,
COL2,
COL3
}
enum SUBGROUP2 implements GROUPMAIN1 {
COL3,
COL4
}
}
因此,要获得枚举,您需要使用.GROUPMAIN1.SUBGROUP1.COL1
如果您只需要一个字符串常量,也可以用另一种方式完成:
public interface GROUPMAIN1 {
interface SUBGROUP1 {
String COL1 = "COL1";
String COL2 = "COL2";
}
interface SUBGROUP2 {
String COL3 = "COL3";
String COL4 = "COL4";
}
}
你不能拥有你所要求的一切。以下是获取其中一些内容的一种方法:
enum MainGroup { GROUP_MAIN1, GROUP_MAIN2 };
enum Subgroup {
SUBGROUP1(MainGroup.GROUP_MAIN1), SUBGROUP2(MainGroup.GROUP_MAIN1),
SUBGROUP3(MainGroup.GROUP_MAIN2), SUBGROUP4(MainGroup.GROUP_MAIN2);
MainGroup main;
private Subgroup(MainGroup main) {
this.main = main;
}
public MainGroup getMainGroup() {
return main;
}
}
enum Col {
COL1(Subgroup.SUBGROUP1), COL2(Subgroup.SUBGROUP1), COL3(Subgroup.SUBGROUP2), COL4(Subgroup.SUBGROUP2),
COL5(Subgroup.SUBGROUP3), COL6(Subgroup.SUBGROUP3), COL7(Subgroup.SUBGROUP4), COL8(Subgroup.SUBGROUP4);
Subgroup sub;
private Col(Subgroup sub) {
this.sub = sub;
}
public MainGroup getMainGroup() {
return sub.getMainGroup();
}
public Subgroup getSubgroup() {
return sub;
}
}
您还可以实现一个方法来查找该主组下的所有子组,对于子组和列也是如此。MainGroup