Search code examples
javajakarta-eeenumsapache-commons

Why does getEnum return null when the enum object exists?


I'm looking at a class similar to the one below. I changed the class name and variable names to avoid putting the actual company names on here (sorry).

import org.apache.commons.lang.enums.Enum;

public class Animal extends Enum {

    public static final Animal DOG = new Animal("Dog");
    public static final Animal CAT = new Animal("Cat");

    private Animal(String name) {
        super(name);
    }

    public static Animal getAnimal(String code) {
        return (Animal) getEnum(Animal.class, code);
    }
}

When getAnimal is passed "Dog" as a parameter it returns an Animal. However, when passed "Cat" as a parameter, it returns null. Why might something like this happen?


Solution

  • In modern Java, you'd write:

    enum Animal {
        Dog, Cat;
    }
    

    and use

    Animal.valueOf(name)
    

    to get the enum value from its name. (Enum types have been added in Java 5, which was released more than 7 years ago.)

    If you are still stuck on a Java version that doesn't support enums, one approach would be to debug org.apache.commons.lang.enums.Enum.getValue. The implementation is hardly going to be rocket science ;-)