通过反射查找可空属性

时间:2015-08-10 13:17:20

标签: kotlin

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

val cls = javaClass<T>().kotlin

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

    }
}

1 个答案:

答案 0 :(得分:9)

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

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