所以我有一个带有多个枚举的Java类
public class Enumerations {
public enum Days {
Monday("MON")
Tuesday("Tue")
string value;
private Days(String value){
this.value = value
}
public string getValue(){
return this.value;
}
}
public enum Months{
January("JAN")
APRIL("APR")
string value;
private Months(String value){
this.value = value
}
public string getValue(){
return this.value;
}
}
}
现在我有另一个类,我想在其中通过字符串访问enum类,因为我无法直接实例化enum,因为我不知道要使用的enum并从可变字符串访问enum值(不知道好)。
class EnumParser{
public static void main(String args[]){
String enum = "Days"; //Will get this value from external source so its variable(Can be months or days)
String value = "Monday" //This is going to variable as well with value unknown.
}
}
那么我如何在这里使用字符串变量将输出显示为“ MON”
Enumerations.{{Days}}.{{Monday}}.getValue();
编辑了问题以获得更清晰的视图,“天”和“星期一”都是变量。
您可以使用if-else
或switch
语句确定要使用的枚举,然后使用valueOf()
:
String e = "Days";
String value = "Monday";
if (e.equalsIgnoreCase(Enumerations.Days.class.getSimpleName())) {
System.out.println(Enumerations.Days.valueOf(value).getValue());
} else if (e.equalsIgnoreCase(Enumerations.Months.class.getSimpleName())) {
System.out.println(Enumerations.Months.valueOf(value).getValue());
} else {
System.out.println("Could not find enum");
}
输出:
MON
根据评论更新,您可能有200多个枚举:
您可以像这样使用反射:
String e = "Days";
String value = "Monday";
String res = Arrays.stream(Enumerations.class.getDeclaredClasses())
.filter(c -> c.getSimpleName().equalsIgnoreCase(e))
.findFirst()
.map(c -> {
String result = null;
try {
Object o = c.getMethod("valueOf", String.class).invoke(null, value);
result = (String) o.getClass().getMethod("getValue").invoke(o);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e1) {
e1.printStackTrace();
}
return result;
}).orElse("Could not find");
System.out.println(res); //prints MON
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句