Is it possible to iterate through several enum classes?

核能气质少年 提交于 2021-02-10 06:01:16

问题


I have three enum classes. I want to somehow put these in an array, loop through the array and call the same method in each enum class. Is this possible in Java?

It seems to me you can't place enum types in an array structure (unless i've missed how).

Thank you.


回答1:


Let each enum type implement a common interface that has the common method that you want into invoke. You can now cast each enum, while iterating, to this common interface and call the method. Also look at EnumSet




回答2:


Here is an example with 2 enums and using reflection:

enum Colour{
    RED,
    BLUE,
    GREEN;

    public void foo(){
        System.out.println("COLOUR");
    }
}

enum Fruit {
    APPLE,
    BANANA,
    PEAR;

    public void foo(){
        System.out.println("FRUIT");
    }
}

You can put the classes into an array and use reflection to call a method for each enum constant:

//create an array
Class[] arr = new Class[2];
arr[0] = Colour.class;
arr[1] = Fruit.class;

//call the foo method
for(Class c : arr){
    Method m = c.getMethod("foo", null);
    for(Object o : c.getEnumConstants()){
        System.out.println("Invoking foo on:" + o);
        m.invoke(o, null);
    }
}



回答3:


If, by enum classes, you mean three different enums, each with their own elements, then you can use an array of type Enum[]. If you mean three items from a single enum, let's call it enum X, then you would put them in an array of type X[].

If you are trying to call a standard Enum function on each one, then you should be all set. If you need to call your own function on them, and are going with an array of Enum[], you'll either need to use reflection or have them all implement the same interface.



来源:https://stackoverflow.com/questions/5354923/is-it-possible-to-iterate-through-several-enum-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!