简体   繁体   中英

How to get value from a Java enum

I have a enum which looks like:

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

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

I have a test class which looks like

public class TestConstants{
 public static void main(String[] args){
   System.out.println(Constants.YES.toString())
   System.out.println(Constants.NO.toString())
 }
}

The output is:

YES
NO

instead of

Y
N

I am not sure what is wrong here ??

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;
    }
}

Write Getter and Setter for value and use:

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

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());
    }
}

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM