Reputation: 453
I'm using enums in Java that just contain constant values and using accessors to retrieve the values e.g
public enum MyConstants {
CONST0(0),
CONST1(1);
private final int code;
private MyConstants(int code) {
this.code = code;
}
public int getCode() {
return this.code;
}
// more accessor type functions etc
}
Now, if I need another enum to store some different constants I don't want to repeat the code for the accessors etc. Is there a way to make some kind of generic enum 'template' so that I can just set up the constants and have the accessor functions for free? I often need to use this kind of enum, so it would be useful to have some kind of template for it.
Is there a nice way to do it? Many Thanks!
Upvotes: 1
Views: 218
Reputation: 69339
Because enums cannot be extended, there is no easy way to do this.
One idea would be to define an interface that your enums will implement. Then, at least, your IDE can help you auto-generate the methods:
public interface ConstantEnum {
int getCode();
}
Alternatively, configure a template in your IDE to speed up the coding.
Upvotes: 3