简体   繁体   English

如何从枚举中提取所有值并将其添加到列表<String>

[英]How to extract all values from an enum an add them to a List<String>

The title is pretty self-explanatory. 标题很不言自明。 Here's my code so far: 到目前为止,这是我的代码:

public List<String> getVoucherStatuses() {
        List<String> listOfStatuses = new ArrayList<String>();

        for (VoucherStatus status : VoucherStatus.values()) {
            listOfStatuses.add(status.name());
        }
        return listOfStatuses;
    }

and here is the Enum: 这是枚举:

public enum VoucherStatus {
        GENERATED, INVALID, ISSUED, REDEEMED, EXPIRED
    }

I keep getting null reference expcetion. 我不断收到空引用期望。 What am I doing wrong? 我究竟做错了什么? Thanks 谢谢

If you're calling this from within the static initialiser of the enum, it wont have finished initialising which may well give you an NPE. 如果您是从枚举的静态初始化程序中调用此函数,则它将不会完成初始化,这很可能会给您带来NPE。

One work around is to use a nested class for the static. 解决方法之一是对静态使用嵌套类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 JSON 数组中提取键的所有值并将它们添加到 List - Extract all values of a key from a JSON array and add them to List 如何从 json 列表中提取两个值并将它们保存到地图中? - How to extract two values from a json list and save them to a map? 如何将枚举添加到枚举列表并遍历它们 - How to add enum to list of enum and loop through them 从“字符串”列表中找到所有数字,并将其相加,然后进行比较(如果等于) - Find all the numbers from the list String and add them and compare if it equals to 从字符串中提取数字并将其添加 - Extract numbers from String and add them 从Enum名称的字符串文字返回Enum值列表 - Return List of Enum values from string literal of Enum's name 如何将字符串列表中的所有值添加到单个字符串? - How can I add all the values in the string list to a single string? 如何从数组列表中提取数字,将它们相加并除以数组列表中的数字数量? - How to extract numbers from an array list, add them up and divide by the amount of numbers in the array list? 检查 Enum 是否包含列表中存在的所有值<string></string> - Check if Enum contains all the values present in a List<String> 如何从Java中的Enum值返回具有所有属性的Enum对象 - How to Return Enum objects with all properties from Enum values in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM