I have an entity that has an enum property:
// MyFile.java
public class MyFile {
private DownloadStatus downloadStatus;
// other properties, setters and getters
}
// DownloadStatus.java
public enum DownloadStatus {
NOT_DOWNLOADED(1),
DOWNLOAD_IN_PROGRESS(2),
DOWNLOADED(3);
private int value;
private DownloadStatus(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
I want to save this entity in database and retrieve it. The problem is that I save the int value in database and I get int value! I can not use switch like below:
MyFile file = new MyFile();
int downloadStatus = ...
switch(downloadStatus) {
case NOT_DOWNLOADED:
file.setDownloadStatus(NOT_DOWNLOADED);
break;
// ...
}
What should I do?
You could provide a static method in your enum:
Then in your main code:
The advantage of this vs. the ordinal approach, is that it will still work if your enum changes to something like:
Note that the initial implementation of the
getStatusFromIntmight use the ordinal property, but that implementation detail is now enclosed in the enum class.