来自Java的Kotlin:字段是否可以为空? [英] Kotlin from Java: is a field nullable or not?

查看:63
本文介绍了来自Java的Kotlin:字段是否可以为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Java访问Kotlin类时,是否可以在运行时告知特定字段是否可为空?此外,是否可以判断一个类是否是一个数据类?

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.

推荐答案

如果你有一个 java.lang.reflect.Field 一个属性的实例,你可以先用<$ c $将它转换为 kotlin.reflect.KProperty 实例来获取该属性的原始Kotlin表示。 c> kotlin.reflect.jvm.ReflectJvmMapping ,然后获取类型并检查其可为空性或其他任何内容:

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:字段是否可以为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆