2017-10-10 24 views
1
public enum EnumCountry implements EnumClass<Integer> { 

    Ethiopia(1), 
    Tanzania(2), 
    private Integer id; 

    EnumCountry(Integer value) { 
    this.id = value; 
    } 

    public Integer getId() { 
    return id; 
    } 

    @Nullable 
    public static EnumCountry fromId(Integer id) { 
    for (EnumCountry at : EnumCountry.values()) { 
     if (at.getId().equals(id)) { 
     return at; 
     } 
    } 
    return null; 
    } 
} 

我有類似上面的代碼。 如何使用Enum名稱獲取Enum ID。如何使用枚舉名得到enum id

+1

的可能重複的https:/ /stackoverflow.com/questions/604424/lookup-enum-by-string-value – wds

回答

1

這是因爲調用它的getId()方法非常簡單:

Ethiopia.getId() 

或者:

Tanzania.getId() 

或者,假設你的意思是你有串"Ethiopia",那麼你也可以做EnumCountry.valueOf("Ethiopia").getId()。希望這能回答你的問題!

6
public static int getId(String enumCountryName) { 
    return EnumCountry.valueOf(enumCountryName).getId(); 
    } 

所以完整的類會是這樣 -

public enum EnumCountry implements EnumClass<Integer> { 

    Ethiopia(1), 
    Tanzania(2), 
    private Integer id; 

    EnumCountry(Integer value) { 
    this.id = value; 
    } 

    public Integer getId() { 
    return id; 
    } 

    @Nullable 
    public static EnumCountry fromId(Integer id) { 
    for (EnumCountry at : EnumCountry.values()) { 
     if (at.getId().equals(id)) { 
     return at; 
     } 
    } 
    return null; 
    } 

public static int getId(String enumCountryName) { 
    return EnumCountry.valueOf(enumCountryName).getId(); 
    } 
} 
1

你不能因爲他們的類型不兼容 - 即String VS Integer。在另一方面,你可以添加返回String,結合nameid的方法:

public enum EnumCountry implements EnumClass<Integer> { 

    Ethiopia(1), 
    Tanzania(2); // replaced comma with semicolon 

    private Integer id; 

    // ... 

    public String getNameId() { 
     // returns "Ethiopa 1" 
     return name() + " " + id; 
    } 

    // ... 
} 
1

如果名字是存在String,簡單地做到這一點,

int getId(String name){ 
    EnumCountry country = EnumCountry.valueOf(name); 
    return country.getId(); 
}