'Set enum field to default value in case no value is passed

I have a gender enum like this:

public enum GenderEnum {
    INVALID,
    MALE,
    FEMALE;

    public static GenderEnum from(String text) {
        if (text == null) {
            return INVALID;
        } else {
            return valueOf(text);
        }
    }
}

I have another class which uses a reference of GenderEnum. There could be instances when we won't get any value for gender, in such cases, the call fails with message could not convert attribute. How can I make it set to INVALID by default?

Example

 public class User {
 
     //.... other fields ....
     private GenderEnum gender; 
 }


Solution 1:[1]

The method valueOf(String) return Expection when argument is invalid :

  • IllegalArgumentException if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type
  • NullPointerException if enumType or name is null

You can write:

public static GenderEnum from(String text) {
    GenderEnum gender;

    try {
        gender = valueOf(text);
    } catch (IllegalArgumentException | NullPointerException e) {
        gender = INVALID;
    }
    
    return gender;
}

Or simplify:

public static GenderEnum from(String text) {
    GenderEnum gender = INVALID;

    try {
        gender = valueOf(text);
    } catch (Exception ignore) { }
    
    return gender;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yannis Sauzeau