gpt4 book ai didi

kotlin - 有没有办法从 'String' 转换为 'KType' ?

转载 作者:行者123 更新时间:2023-12-02 12:41:17 26 4
gpt4 key购买 nike

简单地说,我想要一个像这样的函数:

fun <T> convert(val foo: String, fooT: KType) : T {
...?
}

对于Int,它将返回foo.toInt(),对于Double,返回foo.toDouble(),对于某些未知类型,只抛出异常。我认为为我期望的类型创建我自己的 switch 语句并不难,但出于好奇 - 已经有办法了吗?

最佳答案

推荐方式

不幸的是,没有简单的通用方法,因为我们不是在处理强制转换,而是在处理方法调用。这将是我的方法:

fun <T> convert(str: String, type: KType) : T {

val result: Any = when (type.jvmErasure)
{
Long::class -> str.toLong()
Int::class -> str.toInt()
Short::class -> str.toShort()
Byte::class -> str.toByte()
...
else -> throw IllegalArgumentException("'$str' cannot be converted to $type")
}

return result as T // unchecked cast, but we know better than compiler
}

用法:

@UseExperimental(ExperimentalStdlibApi::class)
fun main() {

val int = convert<Int>("32", typeOf<Int>())

println("converted: $int")
}

而不是 KType参数,你也可以使用 Class<T>并使函数具体化,所以它可以被称为convert<Int>("32")甚至 "32".toGeneric<Int>() .


硬核方式

虽然没有简单的方法,但可以使用大量反射并依赖于实现细节来访问类型。为此,我们可以从 KType 中提取类型名称。对象,找到匹配的扩展方法(在不同的类中),并使用反射调用它。

我们必须使用 to*OrNull()而不是 to*() ,因为后者是内联的,不会被反射找到。此外,我们需要求助于 Java 反射——此时,Kotlin 反射抛出 UnsupportedOperationException。对于所涉及的类型。

我不建议在生产代码中这样做,因为它效率低下并且可能会破坏 future 的标准库版本,但这是一个不错的实验:

fun convert(str: String, type: KType): Any {
val conversionClass = Class.forName("kotlin.text.StringsKt")
// here, the to*OrNull() methods are stored
// we effectively look for static method StringsKt.to*OrNull(String)

val typeName = type.jvmErasure.simpleName
val funcName = "to${typeName}OrNull" // those are not inline

val func = try {
conversionClass.getMethod(funcName, String::class.java) // Java lookup
} catch (e: NoSuchMethodException) {
throw IllegalArgumentException("Type $type is not a valid string conversion target")
}

func.isAccessible = true // make sure we can call it
return func.invoke(null, str) // call it (null -> static method)
?: throw IllegalArgumentException("'$str' cannot be parsed to type $type")
}

关于kotlin - 有没有办法从 'String' 转换为 'KType' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58744044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com