Conveniently map between enum and int / String

前端 未结 18 1822
陌清茗
陌清茗 2020-11-28 01:07

When working with variables/parameters that can only take a finite number of values, I try to always use Java\'s enum, as in

public enum BonusT         


        
18条回答
  •  Happy的楠姐
    2020-11-28 01:33

    Seems the answer(s) to this question are outdated with the release of Java 8.

    1. Don't use ordinal as ordinal is unstable if persisted outside the JVM such as a database.
    2. It is relatively easy to create a static map with the key values.

    public enum AccessLevel {
      PRIVATE("private", 0),
      PUBLIC("public", 1),
      DEFAULT("default", 2);
    
      AccessLevel(final String name, final int value) {
        this.name = name;
        this.value = value;
      }
    
      private final String name;
      private final int value;
    
      public String getName() {
        return name;
      }
    
      public int getValue() {
        return value;
      }
    
      static final Map names = Arrays.stream(AccessLevel.values())
          .collect(Collectors.toMap(AccessLevel::getName, Function.identity()));
      static final Map values = Arrays.stream(AccessLevel.values())
          .collect(Collectors.toMap(AccessLevel::getValue, Function.identity()));
    
      public static AccessLevel fromName(final String name) {
        return names.get(name);
      }
    
      public static AccessLevel fromValue(final int value) {
        return values.get(value);
      }
    }
    

提交回复
热议问题