16

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

私は何をすべきか?

4

2 に答える 2

28

列挙型に静的メソッドを指定できます。

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序数プロパティを使用する場合がありますが、実装の詳細はenumクラスに含まれていることに注意してください。

于 2013-01-04T09:58:25.560 に答える
12

すべてのJava列挙型には自動的に割り当てられる序数があるため、intを手動で指定する必要はありません(ただし、序数は1ではなく0から始まることに注意してください)。

次に、序数から列挙型を取得するには、次のようにします。

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

...次に、列挙型を使用して切り替えを行うことができます...

switch (ds)
{
  case NOT_DOWNLOADED:
  ...
}
于 2013-01-04T09:55:43.913 に答える