我当前有一个字段转换为对象。我需要检查该字段是否是枚举类型,如果是,我想获取当前设置值的名称。 任何想法将不胜感激。
If(field is an enum){
get the value of the field
}
我现在在哪里
if (field.getClass().isEnum()){
String enumValue = //here i need to cast the field to enum and do something like field.name()
}
最佳答案
基于
I have a field currently casted to object
我假设您遇到类似 Object obj = SomeEnum.FOO;
和来自
i would like to get the name of the currently set value
我假设您想获得“FOO”
字符串。
如果上述假设正确,那么您所写的内容
String enumValue = //here i need to cast the field to enum and do something like field.name()
应该适合你。因此,当您确定 field
包含枚举值时,您可以将其转换为 Enum
类型并调用其返回 String 的 name()
方法代表枚举值。
String enumValue = ((Enum)field).name();
如果您确定枚举不会覆盖其 toString()
方法,您也可以调用它,因为默认情况下它也会返回枚举的 name
。
String enumValue = field.toString(); //this solution looks nicer but first one is more reliable.
关于java - 如何在 Java 中将对象转换为 Enum 并获取当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58218034/