I've never really made use of Java enum classes before for constant values, I've typically used the "public final" approach in the past. I've started using an enum now and I'm overriding the toString() method to return a different value than the enum name.
I have some JPA code in which I'm creating a TypedQuery with named parameters, one of which is a String representation of the enum value. If I merely set the parameter using Status.ACTIVE, I get the proper "A" value, but an exception is thrown because it's type is actually Status rather than String. It only works if I explicitly call the toString() method. I thought that simply overriding the toString() method would result in a String type being returned, no matter what the class type was.
This is the enum:
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 the 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());
The toString() method of Enum class returns the name of this enum constant, as the declaration contains. The toString() method can be overridden, although it's not essential.
We can override the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
The Java Enum has two methods that retrieve that value of an enum constant, name() and toString().
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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With