java enum

less than 1 minute read

enum type

enum Level {
  LOW,
  MEDIUM,
  HIGH
}

public class Main {
  public static void main(String[] args) {
    Level myVar = Level.MEDIUM;

    switch(myVar) {
      case LOW:
        System.out.println("Low level");
        break;
      case MEDIUM:
         System.out.println("Medium level");
        break;
      case HIGH:
        System.out.println("High level");
        break;
    }
  }
}

// Loop Through an Enum
for (Level myVar : Level.values()) {
  System.out.println(myVar);
}

Result:

LOW
MEDIUM
HIGH

enum java file

// TestCode.java
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

@Getter
@Slf4j
public enum TestCode {
    DEBUG("debugging", 1),
    INFO("information", 2),
    WARNING("information", 3),
    ERROR("error", 4),
    FATAL("fatal error", 5),
    ALARM("alarm(sms, webhook, ...)", 6);

    private String desc;
    private int level;

    TestCode(String desc, int level) {
        this.desc = desc;
        this.level = level;
    }
    public static void printList() {
        for (TestCode myVar : TestCode.values()) {
            log.info("Code[{}] : {}, {}", myVar.toString(), myVar.getDesc(), myVar.getLevel());
        }
    }
}

Output of printList():

Code[DEBUG] : debugging, 1
Code[INFO] : information, 2
Code[WARNING] : information, 3
Code[ERROR] : error, 4
Code[FATAL] : fatal error, 5
Code[ALARM] : alarm(sms, webhook, ...), 6

Tags:

Categories:

Updated:

Leave a comment