reflection - 获取可为空类型的类
问题描述
我正在尝试匹配String?
Kotlin 反射练习中可为空的类型:
data class Test(a: String, b: String?)
val test = Test("1", "2")
val properties = test::class.declaredMemberProperties
val propertyNames = properties.joinToString(",") {
when (it.returnType) {
String?::class.createType() -> "string?"
String::class.createType() -> "string"
else -> throw Exception()
}
}
唉,它因错误而失败,Type in a class literal must not be nullable
, for String?::class
。
解决方案
该createType
函数有一个可选的可空参数,当我测试它时似乎可以工作。
import kotlin.reflect.full.*
String::class.createType(nullable = true) -> "string?"
推荐阅读
- php - WordPress wp-insert-post 函数创建任意无标题页面
- asp.net-mvc - mvc 站点上的主机名无效 - IIS 8
- php - 通过 HTTP 以 1k 块传输任何类型的文件
- java - Javafx 滑块拇指
- python - wtforms/flask_wtf 验证器:FileAllowed,不捕获禁止的文件扩展名
- c# - Unity 3D:带有玩家健康的 NullReferenceException
- java - IntelliJ 测试失败
- java - 如何防止通过 WebClient 进行多次身份验证调用
- c# - 仅在调试模式“CefSharp.Core.Runtime”版本 89.0.170 上找不到 CefSharp WPF 文件
- angular - Angular Prerender 为 260 个字符以下的文件路径引发 ENAMETOOLONG 错误