Question

I have below enum

public static enum STATUS{
 STRTD, COMP
}

I want to give more meaning to the enum and make enum attributes easily recognisable in coding. But I am not able to modify enum as below-

public static enum STATUS{
 STARTED("STRTD"), COMPLETED("COMP")
}

Kindly suggest its possible. If possible then where am I doing wrong.

Était-ce utile?

La solution

This is because you need to define a constructor for your enum. Add a proper constructor:

public static enum STATUS{
    STARTED("STRTD"), COMPLETED("COMP");
    public final String status;
    private STATUS(String status) {
        this.status = status;
    }
}

Now you can access to this field from your enums:

System.out.println(STATUS.STARTED.status);

Just in case you will use this enum in tools used to the JavaBean standard (as pointed out by @chrylis):

public static enum STATUS{
    STARTED("STRTD"), COMPLETED("COMP");
    private final String status;
    private STATUS(String status) {
        this.status = status;
    }
    public String getStatus() {
        return this.status;
    }
}

Autres conseils

public enum Status {
    STARTED("STRTD"), COMPLETED("COMP");

    private String name;

    private Status(String name) {
        this.name = name
    }

    public String getName() {
        return this.name;
    }
}
public enum Status{ 

  STARTED("STRTD"), COMPLETED("COMP");
   private String status;

  Status(String status) {
    this.status=status;
  }
 }

getNameByCode method can be added to the enum to get name of a String value-

enum CODE {
    SUCCESS("SCS"), DELETE("DEL");

    private String status;

    /**
     * @return the status
     */
    public String getStatus() {
        return status;
    }

    /**
     * @param status
     *            the status to set
     */
    public void setStatus(String status) {
        this.status = status;
    }

    private CODE(String status) {
        this.status = status;
    }

    public static String getNameByCode(String code) {
        for (int i = 0; i < CODE.values().length; i++) {
            if (code.equals(CODE.values()[i].status))
                return CODE.values()[i].name();
        }
        return null;
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top