Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using enum in switch/case

Tags:

java

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?

like image 732
Ali Behzadian Nejad Avatar asked Jan 04 '13 09:01

Ali Behzadian Nejad


Video Answer


1 Answers

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.

like image 190
assylias Avatar answered Oct 14 '22 18:10

assylias