Kotlin 通过反射查找可为空的属性

Kotlin 通过反射查找可为空的属性,kotlin,Kotlin,有没有办法列出允许返回null的对象的所有属性 val cls = javaClass<T>().kotlin for(property in cls.properties) { if(property.accessible) { //Is it nullable? } } val cls=javaClass().kotlin for(cls.properties中的属性){ if(property.accessible){ //它可以为空吗?

有没有办法列出允许返回null的对象的所有属性

val cls = javaClass<T>().kotlin

for(property in cls.properties) {
    if(property.accessible) {
        //Is it nullable?

    }
}
val cls=javaClass().kotlin
for(cls.properties中的属性){
if(property.accessible){
//它可以为空吗?
}
}

您正在寻找的API是在最新的Kotlin版本(0.13.213+)中引入的。现在,您可以获取属性的类型,并确定它在源代码中是否标记为可为null:

val property = ...
if (property.returnType.isMarkedNullable) {
    ...
}

您是否尝试查找@Nullable annotations?@D3xter这将不起作用,因为Kotlin使用的Nullable annotation在运行时未被保留。从M13版本开始,现在可以使用Kotlin反射进行此操作谢谢。没有returnType,API有点不完整。