简体   繁体   中英

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.

One work around is to use a nested class for the static.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM