Iterate enum values using java generics

前端 未结 10 1000
余生分开走
余生分开走 2020-12-02 10:55

I\'m trying to find a way to iterate through an enum\'s values while using generics. Not sure how to do this or if it is possible.

The following code illustrates

10条回答
  •  渐次进展
    2020-12-02 11:34

    This is a hard problem indeed. One of the things you need to do is tell java that you are using an enum. This is by stating that you extend the Enum class for your generics. However this class doesn't have the values() function. So you have to take the class for which you can get the values.

    The following example should help you fix your problem:

    public > void enumValues(Class enumType) {
            for (T c : enumType.getEnumConstants()) {
                 System.out.println(c.name());
            }
    }
    

提交回复
热议问题