简体   繁体   中英

What are the drawbacks of enums in Java?

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?

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.

1. It is much like class it's extend java.lang.Enum so you can't extend other enum. Another potential problem is you don't get along with Expression Language (EL) in JSP.

2. There are things that can be done in normal classes but maybe you can not do with enum class because of it is a special class. For example, accessing a static field in the constructor that not possible with enum.

3. When you working with JSP then you can not be accessing enums nor
calling enum constants because it's not supported (which is possible after EL version 3.0)

These are Major drawback.

.

If a value is only really meant to be referenced as a String, then I would leave it as a String constant for simplicity's sake.

Enums are more complicated than String constants with additional functionality and nuance. Check out this question about the difference between an enum's toString and name methods.

If you ever need to change the value of a String constant, it is a one-line change. With an enum it can get more complicated due to having separate values for name and toString, and those values possibly being used in conditional logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM