Reputation: 113
I want to get the enum value by name string,
this the enum code: package practice;
enum Mobile {
Samsung(400),
Nokia(250),
Motorola(325);
int price;
Mobile(int p) {
price = p;
}
int showPrice() {
return price;
}
}
I can get the class name and the name string
Class enumClass = Class.forName("practice.Mobile");
String name = "Samsung";
how can I get the Samsung value 400 only use enumClass and name? thanks a lot
Upvotes: 1
Views: 3398
Reputation: 48307
as you may know, there is a valueOf method in every enum, which returns the constant just by resolving the name(read about exceptions when the string is invalid.)
now, since your enum has another fields associated to the constants you need to search its value by matching those fields too...
this is a possible solution using
public enum ProgramOfStudy {
ComputerScience("CS"),
AutomotiveComputerScience("ACS"),
BusinessInformatics("BI");
public final String shortCut;
ProgramOfStudy(String shortCut) {
this.shortCut = shortCut;
}
public static ProgramOfStudy getByShortCut(String shortCut) {
return Arrays.stream(ProgramOfStudy.values()).filter(v -> v.shortCut.equals(shortCut)).findAny().orElse(null);
}
}
so you can "resolve" the enum by searching its "shortcut"
like
System.out.println(ProgramOfStudy.getByShortCut("CS"));
Upvotes: 2
Reputation: 441
You can use something like:
final Mobile mobile = Mobile.valueOf("Samsung");
final int price = mobile.showPrice();
(you do have to change the scope of the method showPrice()
to public
).
Upvotes: 5