I have an interesting requirement, we have large enums of the form
public enum BpcCmsError {
ERROR_TYPE_1("Error message 1"),
ERROR_TYPE_2("Error message 2"),
ERROR_TYPE_3("Error message 3");
private int errorCode;
private final String errorMessage;
public static final int ERRORCODE_BASE = 100;
I need to assign some unique error codes, starting from a number and counting up, so I have a constructor :
private BpcCmsError(String message) {
this.errorMessage = message;
}
and a static block
static {
int code = ERRORCODE_BASE;
for (BpcCmsError error : EnumSet.allOf(BpcCmsError.class)) {
error.errorCode = ++code;
}
}
which works just fine.
However, I need some added flexibility in assigning these error codes, ideally like this :
ERROR_TYPE_1("Error message 1"),
ERROR_TYPE_2("Error message 2"),
ERROR_TYPE_3(200,"Error message for code");
with the intention that a 2-args constructor would cause subsequent error codes to start from the value of that first parameter. In my case, the error codes will be 100, 101, 200, 201, etc. Of course I need to check that this jump should be permitted, we may already have counted past 200, for example. Any tips on how to achieve this using enums in Java?
nextCodeand either take next code from it and increment it or use code from constructor (after checking validity) and setnextCodeto given code + 1error: illegal reference to static field from initializer.