I’m trying to write some Java code for a set of enum classes.
Each of the enums encapsulate some conceptually distinct data, so it doesn’t make sense to combine them. The enums also map to values in a database, and so also share some common operations, both instance and static operations, related to loading data from the database.
I need to generalise the set of enum classes I have, such that I can pass any one of these enums into a different class which performs and caches of database lookups relating to each of the different enums.
Since the cache/lookup class will also depend on the public and static methods defined in each enum, how can I code my solution so that I can guarantee that any enum that can be passed into the class will have the required methods?
The normal approach would be to define an interface, but interfaces don’t allow static methods.
Alternatively, you might use an abstract class to define the interface and some of the common implementation, but I don’t believe that is possible with enums (I understand that enums must extend the Enum class and cannot be extended).
What are my options do I have that enable me to ensure all of my enums implement the methods I need?
Example enum:
public enum MyEnum{
VALUE_ONE("my data");
VALUE_TWO("some other data");
/**
* Used when mapping enums to database values - if that sounds odd,
* it is: it's legacy stuff
*
* set via private constructor
*/
private String myValue;
//private constructor not shown
public static MyEnum lookupEnumByString(String enumValue){
//find the enum that corresponds to the supplied string
}
public String getValue(){
return myValue;
}
}
It’s all quite complicated and there may be errors, but I hope you get the idea.
It’s a bit strange, that you’re using another String in addition to Enum.name(), do you need it?
Because of all enums extending Enum, you can’t let them share any code. The best you can do is delegating it all to a helper static method in a utility class.
There’s no way to force classes to implement a static method, which is understandable, since there’s no way (except for reflection) to call them.