Kotlin. 如何通过反射检查字段是否可空?

16

我正在开发一款代码生成器,可以在运行时从类中获取数据。该生成器仅适用于Kotlin。目前,我遇到了一个问题,就是不知道如何检查字段是否可为空。

因此,主要问题是如何通过反射来实现这个检查?

1个回答

20

您可以使用 isMarkedNullable 来检查 nullability。以下是示例代码:

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

以下是文档的摘录(重点标记为我的):

For Kotlin types, it means that null value is allowed to be represented by this type. In practice it means that the type was declared with a question mark at the end. For non-Kotlin types, it means the type or the symbol which was declared with this type is annotated with a runtime-retained nullability annotation such as javax.annotation.Nullable.

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 
}

你能提供文档链接吗? - Kirill Rakhman
抱歉,错过了。 - Kirill Rakhman
在Java方面,是否也有关于可空性的表示?即,可空性的信息必须存在于类文件中的某个地方,您如何通过Java反射访问它? - Mirko Klemm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接