Being fairly new to real-world java development, i find myself looking for solutions to things that i’m used to doing in .NET / C#. For example, in .NET, if i wanted to create a representation of various statuses for something, i would do:
public enum MyStatusEnum {
Created = 10,
Initialized = 20,
Active = 30,
Deleted = 40
}
In this case, the .NET runtime would treat this as a number so you can simply cast back and forth between the Enumeration and the Integer. This would allow me to do a few things:
- I can simply store this value in a database integer field – not requiring a table to hold the possible status values
- In this example, where the enum represents a workflow, i can pull items sorted by this status right from the DB
- I intentionally leave some space in between the integers so that if i need to, i could insert a new value if we add a new status, and the existing records wouldn’t need to be updated
So i was looking for a way to do something similar in java. But it turns out, enumerations are represented totally differently in java. As you would expect, as with everything else, enums are objects. This means you can’t cast to an integer when wanting to store this value in a database. A popular solution to this is to use the values() method on the enumeration (returns an array), and loop through them all, checking if it’s the one you want and then use the ordinal as your integer representation.
There’s a few problems with this method
- Seems that the general consensus is that values() is slow
- If the enumeration changes, existing records would need to be updated OR you would lose the ability to let the database sort for you.
However, there’s a class called EnumMap, and it can store your enum representation for you. After a little while, i came up with the following. Because it still has to loop to find the appropriate value, i’m not sure if it’s the best way.
public enum MyStatusEnum {
//the values
Created,
Initialized,
Active,
Deleted;
//look up the integer value for this
public int getCode(){
return _map.get(this);
}
//this will hold the mapping of enum value to corresponding integer value
private static EnumMap<MyStatusEnum, Integer> _map;
//static constructor/initializer will set the corresponding integer values for each enum value
static{
_map = new EnumMap<>(MyStatusEnum.class);
_map.put(MyStatusEnum.Created, 10);
_map.put(MyStatusEnum.Initialized, 20);
_map.put(MyStatusEnum.Active, 30);
_map.put(MyStatusEnum.Deleted, 40);
}
//get the enum value that matches the specified integer
public static MyStatusEnum fromInt(int statusCode){
for(MyStatusEnum status : _map.keySet()){
if(_map.get(status) == statusCode)
return status;
}
throw new RuntimeException("This would be a custom exception class");
}
}
No comments:
Post a Comment