I'm developing a code generator that takes the data from the classes during runtime. This generator is designed to work only with Kotlin. At the moment, I was faced with the problem, as I don't know how to check if the field is nullable.

So the main question is how to implement this check via reflection?

推荐答案

You can check nullability with isMarkedNullable. The following code:

class MyClass(val nullable: Long?, val notNullable: MyClass)
MyClass::class.declaredMemberProperties.forEach {
    println("Property $it isMarkedNullable=${it.returnType.isMarkedNullable}")
}

将打印:

Property val MyClass.notNullable: stack.MyClass isMarkedNullable=false
Property val MyClass.nullable: kotlin.Long? isMarkedNullable=true

摘自documentation(我的重点):

对于Kotlin类型,这意味着允许使用null值

Note that even if isMarkedNullable is false, values of the type can still be null. This may happen if it is a type of the type parameter with a nullable upper bound:

fun <T> foo(t: T) {
    // isMarkedNullable == false for t's type, but t can be null here 
}

Kotlin相关问答推荐

Kotlin Coroutine()是如何工作的?S阻止了.

如何检测一个值是否是Kotlin中的枚举实例?

ActivityResultContracts TakePicture 结果总是返回 false

如何使用 Mockk 模拟返回值类的 Kotlin 函数类型?

如果不在可组合函数中,如何获取 stringResource

Kotlin 数据类中的大量参数

在 Kotlin 中,我可以在集合上有一个条件构建器元素吗?

Kotlin 插件之间的区别

异常传播如何在 CoroutineScope.async 上工作?

Kotlin - 创建指定长度的随机整数的 ArrayList?

Kotlin 1.2.21 + SimpleXml 2.3.0 - consume List error (must mark set get method)

如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

launch 仅从 Kotlin 1.3 开始可用,不能在 Kotlin 1.2 中使用

Kotlin Native如何将字节数组转换为字符串?

如何在 Jetpack Compose 的 LazyColumn/LazyRow 中禁用和启用滚动?

大小写敏感性 Kotlin / ignoreCase

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props

Kotlin 错误:public function exposes its 'public/*package*/' return type argument

带有注释为@RegisterExtension的字段的 JUnit 5 测试在 Kotlin 中不起作用

在 intelliJ 元素中集成 Kotlinx 协程