Let's say I have a string with a value
'Language'
And I have an enum called Language
enum Language{
English,
Spanish,
French
}
Is there a way to use the string 'Language' and return the values of the Enum Language. I'm basically wondering if there is a method to get an instance of the Enum Language by passing in a string. Kind of like
Class.forName()
but for enums.
An enum is a class, so with the fully qualified name (eg, "com.mydomain.myapp.Language"
) you can get the enum's class from Class.forName
. From there, you can use reflection on the Class object: getEnumConstants gives you all the enum's values, and if you want names instead you can just use .name on the Enum objects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.