科特林。如何通过反射检查字段是否可为空?
Kotlin. How to check if the field is nullable via reflection?
我正在开发一个代码生成器,它在运行时从 类 中获取数据。此生成器旨在仅与 Kotlin 一起使用。此刻,我遇到了这个问题,因为我不知道如何检查该字段是否可以为空。
所以主要的问题是如何通过反射实现这个检查?
您可以使用 isMarkedNullable
检查可空性。以下代码:
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(强调我的):
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
}
我正在开发一个代码生成器,它在运行时从 类 中获取数据。此生成器旨在仅与 Kotlin 一起使用。此刻,我遇到了这个问题,因为我不知道如何检查该字段是否可以为空。
所以主要的问题是如何通过反射实现这个检查?
您可以使用 isMarkedNullable
检查可空性。以下代码:
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(强调我的):
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 benull
. 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 }