using enum in switch/case

前端 未结 2 1385
孤城傲影
孤城傲影 2020-12-30 04:07

I have an entity that has an enum property:

// MyFile.java
public class MyFile {   
    private DownloadStatus downloadStatus;
    // other properties, sette         


        
相关标签:
2条回答
  • 2020-12-30 04:58

    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.

    0 讨论(0)
  • 2020-12-30 04:58

    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:
      ...
    }
    
    0 讨论(0)
提交回复
热议问题