2017-10-10 1 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; 
    } 
} 

Ich habe den Code wie oben. Wie bekomme ich Enum Id mit seinem Enum Name.Wie bekomme ich enum id mit seinem enum name

+1

Mögliche Duplikat https liegt als String://stackoverflow.com/questions/604424/lookup-enum-by-string-value – wds

Antwort

1

Es ist so einfach sein getId() -Methode als Aufruf:

Ethiopia.getId() 

Oder:

Tanzania.getId() 

Oder vorausgesetzt, Sie bedeuten Sie die Zeichenfolge "Ethiopia" hast, dann können Sie auch EnumCountry.valueOf("Ethiopia").getId(). Hoffe das beantwortet deine Frage!

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

So ist die komplette Klasse wird so sein -

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

Sie können nicht, weil ihre Typen sind nicht kompatibel - das heißt String vs Integer. Auf der anderen Seite können Sie eine Methode hinzufügen, die ein String zurückgibt, die name und id kombiniert:

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

Wenn der Name, einfach tun dies,

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