Dmitry Ryadnenko
Dmitry Ryadnenko

Reputation: 22512

Kotlin from Java: is a field nullable or not?

When accessing Kotlin classes from Java, is it possible during runtime to tell if a particular field is nullable or not? Also, is it possible to tell if a class is a data class?

Even a guess would be sufficient for my purposes. Using reflection is also fine.

Upvotes: 15

Views: 1213

Answers (1)

Alexander Udalov
Alexander Udalov

Reputation: 32826

If you have a java.lang.reflect.Field instance for a property, you can first obtain the original Kotlin representation of the property by converting it to the kotlin.reflect.KProperty instance with kotlin.reflect.jvm.ReflectJvmMapping, and then get the type and check its nullability or anything else:

public static boolean isNullable(Field field) {
    KProperty<?> property = ReflectJvmMapping.getKotlinProperty(field);
    return property.getType().isMarkedNullable();
}

Upvotes: 20

Related Questions