Kotlin from Java: is a field nullable or not?

Dmitry Ryadnenko :

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.

Alexander Udalov :

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();
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=450573&siteId=1