javaenumshierarchical

Hierarchical enum in Java


Let's say I have a structure like this:

enter image description here

Is it possible to create an enum that will return the string value of selected cell? For example:

enum.GROUP_MAIN1.SUBGROUP1.COL1

will return value "COL1".

I was looking for nested enums but didn't find the solution to this situation.


Solution

  • You can do this with such trick:

    public interface GROUPMAIN1 {
        enum SUBGROUP1 implements GROUPMAIN1 {
            COL1,
            COL2
        }
        enum SUBGROUP2 implements GROUPMAIN1 {
            COL3,
            COL4
        }
    }
    

    So to get enum you will need to use GROUPMAIN1.SUBGROUP1.COL1.

    It can also be done in another way if all you need is just a string constants:

    public interface GROUPMAIN1 {
        interface SUBGROUP1 {
            String COL1 = "COL1";
            String COL2 = "COL2";
        }
        interface SUBGROUP2 {
            String COL3 = "COL3";
            String COL4 = "COL4";
        }
    }