Java 枚举示例

原文: https://javabeginnerstutorial.com/core-java-tutorial/java-enum-example/

  1. /**
  2. * @author GHajba
  3. *
  4. */
  5. public class Main {
  6. public static void main(final String... args) {
  7. Schedule currentSchedule = new Schedule();
  8. currentSchedule.setWorkday(Workday.FRIDAY);
  9. System.out.println("--------");
  10. if (currentSchedule.getWorkday() == Workday.FRIDAY) {
  11. System.out.println("Hurray! Tomorrow is weekend!");
  12. }
  13. System.out.println("--------");
  14. switch (currentSchedule.getWorkday()) {
  15. case MONDAY:
  16. case TUESDAY:
  17. case WEDNESDAY:
  18. case THURSDAY:
  19. System.out.println("Working and working and...");
  20. break;
  21. case FRIDAY:
  22. System.out.println("Hurray! Tomorrow is weekend!");
  23. break;
  24. default:
  25. System.out.println("Unknown day -.-");
  26. }
  27. System.out.println("--------");
  28. System.out.println("Displaying all Workdays:");
  29. for (Workday w : Workday.values()) {
  30. System.out.println(w);
  31. }
  32. System.out.println("--------");
  33. System.out.println("Displaying all Workdays:");
  34. for (Workday w : Workday.values()) {
  35. System.out.println(w.getRepresentation());
  36. }
  37. }
  38. }

Schedule.java

  1. /**
  2. * @author GHajba
  3. *
  4. */
  5. public class Schedule {
  6. private Workday workday;
  7. public Workday getWorkday() {
  8. return this.workday;
  9. }
  10. public void setWorkday(final Workday workday) {
  11. this.workday = workday;
  12. }
  13. }

Workday.java

  1. /**
  2. * @author GHajba
  3. *
  4. */
  5. public enum Workday implements DatabaseEnum<Workday> {
  6. MONDAY("Monday"),
  7. TUESDAY("Tuesday"),
  8. WEDNESDAY("Wednesday"),
  9. THURSDAY("Thursday"),
  10. FRIDAY("Friday");
  11. private final String representation;
  12. private Workday(final String representation) {
  13. this.representation = representation;
  14. }
  15. public String getRepresentation() {
  16. return this.representation;
  17. }
  18. @Override
  19. public String toString() {
  20. return getRepresentation();
  21. }
  22. @Override
  23. public String toDatabaseString() {
  24. return this.representation;
  25. }
  26. @Override
  27. public Workday fromDatabase(final String representation) {
  28. for (Workday wd : Workday.values()) {
  29. if (wd.representation.equals(representation)) {
  30. return wd;
  31. }
  32. }
  33. return null;
  34. }
  35. }