且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Kotlin中的枚举类和字符串获取原始类型的枚举值

更新时间:2023-01-22 20:39:04

这是一个纯Kotlin版本:

Here's a pure Kotlin version:

@Suppress("UNCHECKED_CAST")
fun getEnumValue(enumClass: Class<*>, value: String): Enum<*> {
    val enumConstants = enumClass.enumConstants as Array<out Enum<*>>
    return enumConstants.first { it.name == value }
}

请注意,它的效率不如Java版本。 java.lang.Enum.valueOf 使用缓存的数据结构,而此版本需要创建一个新的数组以进行迭代。这个版本也是O(n),而Java版本是O(1),因为它在引擎盖下使用了字典。

Note that it's not as efficient as the Java version. java.lang.Enum.valueOf uses a cached data structure while this version needs to create a new array to iterate over. Also this version is O(n) wheras the Java version is O(1) as it uses a dictionary under the hood.

有一个未解决问题,以支持与Java相同的代码(计划在1.3版中使用)。

There is an open issue in the Kotlin bug tracker to support the same code as in Java which is scheduled for 1.3.

这是一个确实很丑的黑客,可以解决通用类型问题:

Here's a really ugly hack to workaround the generic type issue:

private enum class Hack

fun getEnumValue(enumClass: Class<*>, value: String): Enum<*> {
    return helper<Hack>(enumClass, value)
}

private fun <T : Enum<T>>helper(enumClass: Class<*>, value: String): Enum<*> {
    return java.lang.Enum.valueOf(enumClass as Class<T>, value)
}

快速测试表明它正在工作,但我不会依赖它。

A quick test shows that it's working but I wouldn't rely on it.

如果如果可以使用通用类型,则可以使用内置函数 enumValueOf (另请参见 http://kotlinlang.org/docs/reference/enum-classes.html#working-with-enum-constants ):

If the generic type is available, you can use the built-in function enumValueOf (see also http://kotlinlang.org/docs/reference/enum-classes.html#working-with-enum-constants):

enum class Color {
    Red, Green, Blue
}

enumValueOf<Color>("Red")