How to get value from a Java enum

后端 未结 5 2064
旧时难觅i
旧时难觅i 2021-01-02 01:49

I have a enum which looks like:

public enum Constants{
  YES(\"y\"), NO(\"N\")
  private String value;

  Constants(String value){
    this.value = value;
           


        
相关标签:
5条回答
  • 2021-01-02 02:06

    Create a getValue() method in your enum, and use this instead of toString().

    public enum Constants{
     YES("y"), NO("N")
     private String value;
    
     Constants(String value){
      this.value = value;
     }
    }
    
     public String getValue(){
      return value;
     }
    

    And instead of:

    System.out.println(Constants.YES.toString())
    System.out.println(Constants.NO.toString())
    

    (Which are also missing a semi-colon), use

    System.out.println(Constants.YES.getValue());
    System.out.println(Constants.NO.getValue());
    

    Hope this solved your problem. If you do not want to create a method in your enum, you can make your value field public, but this would break encapsulation.

    0 讨论(0)
  • 2021-01-02 02:11

    You can also add a getter to the enumeration and simply call on it to access the instance variable:

    public enum Constants{
        YES("Y"), NO("N");
        private String value;
    
        public String getResponse() {
            return value;
        }
    
        Constants(String value){
            this.value = value;
        }
    }
    
    public class TestConstants{
        public static void main(String[] args){
            System.out.println(Constants.YES.getResponse());
            System.out.println(Constants.NO.getResponse());
        }
    }
    
    0 讨论(0)
  • 2021-01-02 02:14

    Write Getter and Setter for value and use:

    System.out.println(Constants.YES.getValue());
    System.out.println(Constants.NO.getValue());
    
    0 讨论(0)
  • 2021-01-02 02:16
    String enumValue = Constants.valueOf("YES")
    

    Java doc ref: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)

    0 讨论(0)
  • 2021-01-02 02:32

    You need to override the toString method of your enum:

    public enum Constants{
        YES("y"), NO("N")
    
        // No changes
    
        @Override
        public String toString() {
            return value;
        }
    }
    
    0 讨论(0)
提交回复
热议问题