How to get value from a Java enum

后端 未结 5 2076
旧时难觅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.

提交回复
热议问题