简体   繁体   中英

How to add enum to list of enum and loop through them

I have 3 Enum classes : ECode, EStatus, EMessage. I would like to add these three Enums to a list of Enum and loop through them to call method in each Enum class. I would like to group them because the methods inside of these Enum Classes are the same. For example below is the code that I am having:

for (ECode code : ECode.values()) {
            ECode.forNumericValue(123456);
            code.toString();
}

for (EStatus status: EStatus.values()) {
            EStatus.forNumericValue(123456);
            status.toString();
}

for (EMessage message : EMessage.values()) {
            EMessage.forNumericValue(123456);
            message.toString();
}

I would like to group it like:

for(Enum enum : listOfEnumClasses()){
    for (enum value: enum.values()) {
         enum.forNumericValue(123456);
         value.toString();
    }
}

Can anyone give me hint how can I archive it? Thank you

If all of your enums implement a known interface you can create an Iterable that iterates across an array of arrays of them. You can then prime it from the enum's values methods.

interface Common {
    // Chosing `name` here because it exists in all enums - just for simplicity here.
    String name();
}

enum A implements Common{
    One, Two, Three;
}

enum B implements Common{
    Ten, Twenty, Thirty;
}

enum C implements Common{
    Twelve, TwentyFour, ThirtySix;
}

static class Enums<T> implements Iterable<T>{
    private final T[][] enums;

    public Enums(T[]... enums) {
        this.enums = enums;
    }

    @NotNull
    @Override
    public Iterator<T> iterator() {
        return new Iterator<T> () {
            private int i = 0;
            private int j = 0;

            @Override
            public boolean hasNext() {
                return i < enums.length && j < enums[i].length;
            }

            @Override
            public T next() {
                T next = enums[i][j];
                if(++j >= enums[i].length) {
                    i += 1;
                    j = 0;
                }
                return next;
            }
        };
    }
}

private void test() {
    for (Common named : new Enums<Common>(A.values(), B.values(), C.values())) {
        System.out.println(named.name());
    }
}

You should be able to improve this by making it take Iterator<T>... instead of T[]... but I'll leave that to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM