[英]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? 从Java访问Kotlin类时,是否可以在运行时告知特定字段是否可以为空? 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: 如果您有一个属性的java.lang.reflect.Field
实例,您可以先使用kotlin.reflect.jvm.ReflectJvmMapping
将其转换为kotlin.reflect.KProperty
实例,然后获取该属性的原始Kotlin表示。类型和检查其可空性或其他:
public static boolean isNullable(Field field) {
KProperty<?> property = ReflectJvmMapping.getKotlinProperty(field);
return property.getType().isMarkedNullable();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.