Kotlin from Java: is a field nullable or not?

2019-03-24 12:32发布

问题:

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.

回答1:

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


标签: java kotlin