I have an entity that has an enum property:
// MyFile.java
public class MyFile {
private DownloadStatus downloadStatus;
// other properties, sette
You could provide a static method in your enum:
public static DownloadStatus getStatusFromInt(int status) {
//here return the appropriate enum constant
}
Then in your main code:
int downloadStatus = ...;
DowloadStatus status = DowloadStatus.getStatusFromInt(downloadStatus);
switch (status) {
case DowloadStatus.NOT_DOWNLOADED:
//etc.
}
The advantage of this vs. the ordinal approach, is that it will still work if your enum changes to something like:
public enum DownloadStatus {
NOT_DOWNLOADED(1),
DOWNLOAD_IN_PROGRESS(2),
DOWNLOADED(4); /// Ooops, database changed, it is not 3 any more
}
Note that the initial implementation of the getStatusFromInt
might use the ordinal property, but that implementation detail is now enclosed in the enum class.
Every Java enum has an ordinal which is automatically assigned, so you don't need to manually specify the int (but be aware that ordinals start from 0, not 1).
Then, to get your enum from the ordinal, you can do:
int downloadStatus = ...
DownloadStatus ds = DownloadStatus.values()[downloadStatus];
... then you can do your switch using the enum ...
switch (ds)
{
case NOT_DOWNLOADED:
...
}