Java enumeration variable overriding toString ()

I have never used the Java enum classes before for constant values, I usually used the "public final" approach in the past. I started using enum now, and I'm overriding the toString () method to return a different value than the enumeration name.

I have a JPA code in which I create a TypedQuery with named parameters, one of which is a string representation of the enum value. If I simply set the using Status.ACTIVE parameter, I get the correct value "A", but an exception is thrown because it is of type Status, not String. It only works if I explicitly call the toString () method. I thought that simply overriding the toString () method would return a String, regardless of the type of class.

This listing is:

public enum Status {
    ACTIVE ("A"),
    PENDING ("P"),
    FINISHED ("F");

    private final String value;

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

    public String toString() {
        return value;
    }
};

This is TypedQuery:

    TypedQuery<MechanicTimeEvent> query = entityManager().createQuery("SELECT o FROM MechanicTimeEvent o WHERE o.id.mechanicNumber = :mechanicNumber AND o.id.status = :status", MechanicTimeEvent.class);
    query.setParameter("mechanicNumber", mechanicNumber);
    query.setParameter("status", Status.ACTIVE.toString());
+5
source share
6 answers

status MechanicTimeEvent bean ? , status.

@Enumerated(EnumType.STRING)

, :

public enum Status {
   ACTIVE,
   PENDING,
   FINISHED;
}
+3
public enum Status {
    ACTIVE,
    PENDING,
    FINISHED;

    @Override
    public String toString() {
        String name = "";
        switch (ordinal()) {
        case 0:
            name = "A";
            break;
        case 1:
            name = "P";
            break;
        case 2:
            name = "F";
            break;
        default:
            name = "";
            break;
        }
        return name;
    }
};
+5

, . , , JPA A, P, F).

public enum Status {
    A("ACTIVE"),
    P("PENDING"),
    F("FINISHED");

, toString() JPA. .name() ENUM , .

+3

getter :

public String getValue()

:

query.setParameter("status", Status.ACTIVE.getValue());
0

toString - Object, , PrintStream.println( System.out.println) +. .

, getValue, , toString

0
java.lang.Enum said clearly:
 /**
 * Returns the name of this enum constant, exactly as declared in its
 * enum declaration.
 * 
 * <b>Most programmers should use the {@link #toString} method in
 * preference to this one, as the toString method may return
 * a more user-friendly name.</b>  This method is designed primarily for
 * use in specialized situations where correctness depends on getting the
 * exact name, which will not vary from release to release.
 *
 * @return the name of this enum constant
 */
 public final String name()

, "name" . toString().

, enum.

-1

All Articles