在switch / case中使用enum

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

// 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属性,但该实现细节现在包含在枚举类中。

每个Java枚举都有一个自动分配的序数,因此您不需要手动指定int(但要注意,序数从0开始,而不是1)。

然后,为了从序数中获取你的枚举,你可以:

 int downloadStatus = ... DownloadStatus ds = DownloadStatus.values()[downloadStatus]; 

…然后你可以使用enum进行切换…

 switch (ds) { case NOT_DOWNLOADED: ... }