在开关/案例中使用枚举

阿里·贝扎迪安·内贾德(Ali Behzadian Nejad):

我有一个具有枚举属性的实体:

// 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;
    }
} 

我想将此实体保存在数据库中并检索它。问题是我将int值保存在数据库中,并且得到了int值!我不能使用如下所示的开关:

MyFile file = new MyFile();
int downloadStatus = ...
switch(downloadStatus) {
    case NOT_DOWNLOADED:
    file.setDownloadStatus(NOT_DOWNLOADED);
    break;
    // ...
}    

我该怎么办?

亚述:

您可以在枚举中提供一个静态方法:

public static DownloadStatus getStatusFromInt(int status) {
    //here return the appropriate enum constant
}

然后在您的主要代码中:

int downloadStatus = ...;
DowloadStatus status = DowloadStatus.getStatusFromInt(downloadStatus);
switch (status) {
    case DowloadStatus.NOT_DOWNLOADED:
       //etc.
}

此方法与顺序方法相比的优势在于,如果您的枚举更改为以下内容,它将仍然有效:

public enum DownloadStatus {
    NOT_DOWNLOADED(1),
    DOWNLOAD_IN_PROGRESS(2),
    DOWNLOADED(4);           /// Ooops, database changed, it is not 3 any more
}

请注意,的初始实现getStatusFromInt可能使用ordinal属性,但是实现细节现在包含在enum类中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章