如何从Kotlin中的枚举类和字符串获取原始类型的枚举值 [英] How to get enum value of raw type from an enum class and a string in kotlin

查看:982
本文介绍了如何从Kotlin中的枚举类和字符串获取原始类型的枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中具有以下代码:

I have the following code in java:

Enum getEnumValue(Class<?> enumClass, String value) {
    return Enum.valueOf((Class<Enum>) enumClass, value);
}

如何用Kotlin重写它?

How to rewrite this in Kotlin?

更新

enumValueOf<>()函数是在这种情况下不适用,因为我不知道实际的类型参数,我只有一个类型未知的 Class<?> 对象( Class< ; *> 在Kotlin中)和一个名称字符串。已知该类为枚举: Class.isEnum 返回true。使用这两个输入,上面的Java代码允许获取具有原始类型的枚举的值。这正是我所需要的,因为我对枚举的特定类型不感兴趣。但是我不知道如何在Kotlin中获得相同的结果。

enumValueOf<>() function is not applicable in this case because I don't know the actual type parameter, I only have a Class<?> object with unknown type (Class<*> in kotlin) and a name string. The Class is known to be enum: Class.isEnum returns true. Using these two inputs, the java code above allows to obtain the value of the enum with a raw type. That's just what I need because I'm not interested in the specific type of the enum. But I can't figure out how to get the same result in kotlin.

推荐答案

这是一个纯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")

这篇关于如何从Kotlin中的枚举类和字符串获取原始类型的枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆