Kotlin. How to check if a field is a null reflection path?

I am developing a code generator that takes data from classes at runtime. This generator is designed to work only with Kotlin. At the moment, I am faced with a problem, since I do not know how to check if the field is zero.

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

+7
java reflection null nullable kotlin
source share
1 answer

You can check the nullability value with isMarkedNullable . The following code:

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

will print:

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

Excerpt from the documentation (highlighted by me):

For Kotlin types, this means that a null value is allowed represented by this type. In practice, this means that the type has been declared with a question mark at the end. For non-Kotlin types, this means that the type or character that was declared with this type is annotated with a null value annotation stored at runtime, for example, javax.annotation.Nullable.

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

 fun <T> foo(t: T) { // isMarkedNullable == false for t type, but t can be null here } 
+9
source share

All Articles