简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM