How to get enum value from string in Java
Hello everyone! I'm new to Java and encountered a problem when working with enums. I have this enum for order statuses:
```java
public enum OrderStatus {
NEW,
PROCESSING,
SHIPPED,
DELIVERED,
CANCELLED
}
```
I get a string from the database, for example "PROCESSING", and I need to convert it back to the enum value `OrderStatus.PROCESSING`. I tried using simple type casting, but it doesn't work:
```java
String statusStr = "PROCESSING";
OrderStatus status = (OrderStatus) statusStr; // Compilation error
```
I also tried using `valueOf()`, but when the string doesn't match any enum value, it throws an `IllegalArgumentException`. For example, if the user entered "processing" (with lowercase letters)
No answers yet.
Log in to leave an answer
Blogs