Iterate enum values using java generics

前端 未结 10 1036
余生分开走
余生分开走 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:23

    For completeness, JDK8 gives us a relatively clean and more concise way of achieving this without the need to use the synthethic values() in Enum class:

    Given a simple enum:

    private enum TestEnum {
        A,
        B,
        C
    }
    

    And a test client:

    @Test
    public void testAllValues() {
        System.out.println(collectAllEnumValues(TestEnum.class));
    }
    

    This will print {A, B, C}:

    public static > String collectAllEnumValues(Class clazz) {
        return EnumSet.allOf(clazz).stream()
                .map(Enum::name)
                .collect(Collectors.joining(", " , "\"{", "}\""));
    }
    

    Code can be trivially adapted to retrieve different elements or to collect in a different way.

提交回复
热议问题