java tutorial: java enum in switch case

During the development of the java project, we occasionally use enum in the switch case statement.

This article introduces you how to use enum correctly in java switch case statement.

First of all, it needs to be clear:

An enum switch case label must be the unqualified name of an enumeration constant.

Implementation:

  1. Returns the enum constant of the specified enum type with the specified name.
  2. The case label is an enum constant. Note that the enum class name is not required. If the label uses a class name, such as JobStatus.FAILED, a compilation error will be reported.

So, the correct way to write:

        JobStatus jobStatus = JobStatus.valueOf(status);
        switch (jobStatus) {
            case FAILED:
                ...
                break;
            case CREATED:
                ...
                break;
            case FINISHED:
                ...
                break;
            case EXECUTING:
                ...
                break;
        }

Test code:

JobStatus.class

package com.example.Enum;

import org.apache.commons.lang3.StringUtils;

public enum JobStatus {
    CREATED(1, "CREATED"),
    EXECUTING(2, "EXECUTING"),
    FINISHED(3, "FINISHED"),
    FAILED(0, "FAILED");

    Integer code;
    String name;

    JobStatus( Integer code, String name) {
        this.name = name;
        this.code = code;
    }

    public static Boolean isExist(String name) {
        if(StringUtils.isBlank(name)) {
            return false;
        }

        for(JobStatus item : JobStatus.values()) {
            if(name.equals(item.name)) {
                return true;
            }
        }
        return false;
    }
}

TestEnumInSwitch.class
package com.example.Enum;

public class TestEnumInSwitch {
    public static void main(String[] args) {
        String status = "created";

        enumInSwitch(status);
    }

    private static void enumInSwitch(String status) {

        JobStatus jobStatus = JobStatus.valueOf(status.toUpperCase());
        switch (jobStatus) {
            case FAILED:
                System.out.println("jobStatus = FAILED");
                break;
            case CREATED:
                System.out.println("jobStatus = CREATED");
                break;
            case FINISHED:
                System.out.println("jobStatus = FINISHED");
                break;
            case EXECUTING:
                System.out.println("jobStatus = EXECUTING");
                break;
        }
    }
}

Add a Comment

Your email address will not be published.