在switch / case中使用enum [英] using enum in switch/case

查看:1443
本文介绍了在switch / case中使用enum的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我该怎么办?

推荐答案

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

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
}

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

Note that the initial implementation of the getStatusFromInt might use the ordinal property, but that implementation detail is now enclosed in the enum class.

这篇关于在switch / case中使用enum的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆