简体   繁体   中英

Best way to create a Unique ID field for an enum

What is the best way to get a Unique ID from an ENUM that will stay consistent between repeated execution of the program?

Currently I am doing this manually by passing an ID to the enum constructor. I don't really want to do this is I can help it.

Another option would be to use a static field that gets incremented for each enum value. The problem is that if later I decide to move the enum fields around or delete some this will cause problems with my program as the ID will be saved into user preferences.

The ID can be any basic type or a String.

It may be too simple, but what's wrong with "class name + enum name"?

Simply add this method to your enum:

public String getID() {
  return getClass().getName() + "." + name();
}

When creating an enum you can do:

public enum myEnum {
    VAL1("v1"), VAL2("v2");

    private String id;

    private myEnum(String id) { this.id = id };

    public getId() { return id;}
}

Or you can use name() which every enum has which return the name declared, in this case "VAL1" or "VAL2". Both are valid ways to do what you want. When you said you passed the id to the constructor is this what you meant, and if yes, please explain why this isn't helpful to you.

The name of the enum will be held constant. You shouldn't be setting a different value.

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