简体   繁体   English

来自Java的Kotlin:字段是否可以为空?

[英]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.

相关问题 Kotlin - 可空场的非空吸气剂 - Kotlin - nonnull getter for a nullable field 从 Kotlin 将 null 传递给不可为空的 Java 方法 - Pass null to non-nullable Java method from Kotlin Java到Kotlin转换器和可空的方法参数 - Java to Kotlin converter and nullable method arguments 在kotlin中调用java时如何检测可为空 - how to detect nullable when call java in kotlin 我如何知道从 Kotlin 调用 java 方法时是否应在调用站点检查可为空的参数? - How can i know when calling a java method from Kotlin if a nullable argument should be checked at call site? 科特林。如何通过反射检查字段是否可以为空? - Kotlin. How to check if the field is nullable via reflection? 如何从Java隐藏Kotlin的lateinit var支持字段? - How to hide Kotlin's lateinit var backing field from Java? 在Kotlin中覆盖Java @Nullable varargs方法时,IDE抱怨它没有覆盖任何内容 - Overriding a Java @Nullable varargs method in Kotlin, IDE complains it overrides nothing 如何在Kotlin生成的Java代码中禁用@ NonNull / @ Nullable批注 - How to disable @NonNull/@Nullable annotations in Kotlin generated Java code 带有?的对象 Kotlin中的Java转换为@ org.jetbrains.annotations.Null在Java中 - Objects with ? in Kotlin translates to @org.jetbrains.annotations.Nullable in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM