How to ensure completeness in an enum switch at compile time?

后端 未结 12 977
悲&欢浪女
悲&欢浪女 2020-11-27 06:25

I have several switch statements which test an enum. All enum values must be handled in the switch statements by a case s

12条回答
  •  抹茶落季
    2020-11-27 06:42

    In case there are several enums on different tiers of the project that must correspond to each other, this can be ensured by a test case:

    private static > String[] names(T[] values) {
        return Arrays.stream(values).map(Enum::name).toArray(String[]::new);
    }
    
    @Test
    public void testEnumCompleteness() throws Exception {
        Assert.assertArrayEquals(names(Enum1.values()), names(Enum2.values()));
    }
    

提交回复
热议问题