Янислав Корнев Янислав Корнев - 1 year ago 116
Java Question

Kotlin. How to check if the field is nullable via reflection?

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?

Answer Source

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}")

will print:

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

Excerpt from documentation (emphasis mine):

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 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download