有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    您可以做(Java 8之前的版本):

    List<Enum> enumValues = Arrays.asList(Enum.values());
    

    或者

    List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));
    

    使用Java 8功能,您可以将每个常量映射到其名称:

    List<String> enumNames = Stream.of(Enum.values())
                                   .map(Enum::name)
                                   .collect(Collectors.toList());
    
  2. # 2 楼答案

    你也可以做如下事情

    public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
    EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())
    

    或者

    EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())
    

    我偶然发现这个问题的主要原因是,我想编写一个通用验证器,用于验证给定字符串枚举名对给定枚举类型是否有效(如果有人发现有用,请共享)

    对于验证,我必须使用Apache's EnumUtils库,因为在编译时不知道枚举的类型

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
        Set<String> notAllowedNames = enumNames.stream()
                .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
                .collect(Collectors.toSet());
    
        if (notAllowedNames.size() > 0) {
            String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
                .collect(Collectors.joining(", "));
    
            throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                    .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                    + "of the following : " + validEnumNames);
        }
    }
    

    我太懒了,没有像这里https://stackoverflow.com/a/51109419/1225551所示编写枚举注释验证器