What are the drawbacks of enums in Java?

Mathieu Gemard :

While looking at jhipster, I have stumbled across the following class

public final class AuthoritiesConstants {
    public static final String ADMIN = "ROLE_ADMIN";
    public static final String USER = "ROLE_USER";
    public static final String ANONYMOUS = "ROLE_ANONYMOUS";
    private AuthoritiesConstants() {
    }
}

I was wondering why they did not use enums like for example

public enum AuthoritiesConstants {
    ROLE_ADMIN,
    ROLE_RESPONSABLE,
    ROLE_MANAGER,
    ROLE_COLLABORATEUR
}

Are there any drawbacks using enums?

Piotr Wilkin :

One possible answer is that enums were introduced in Java 1.5. While this seems like ancient history, some libraries still use string constants or numeric constants for compatibility reasons.

Another possible answer is that those are not really semantically enum elements, but constants used by an external interface and are only ever accessed via their string value. In such cases, using enums and calling name() each time would be redundant.

Other than that, you should never use enums over string constants in such cases.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310925&siteId=1